tags:

views:

108

answers:

3

What is the easiest way to check in Javascript whether the input text field is empty (contains nothing or white spaces only)?

+1  A: 

You are looking for something like trim function, right?

Sarfraz
Yes, thanks !Actually jQuery has a built-in trim() function !
Misha Moroshko
you didn't say that you were working with jQuery - you get the best answers if you provide more information... the jquery validate plug provides a :blank selector.http://docs.jquery.com/Plugins/Validation/blank
calumbrodie
+1 You are right. I should have mentioned that. Thanks for the :blank !
Misha Moroshko
+1  A: 

Include this function somewhere (in order to provide a trim function)

String.prototype.trim = function () {
   return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

see here http://javascript.crockford.com/remedial.html

then...

if (document.forms['id_of_form'].elements['id_of_input'].value.trim=='') {
    //do xyz
}
calumbrodie
+1  A: 
var str = document.getElementById("myInput").value;
if (str.match(/^\s*$/)) {
    // nothing, or nothing but whitespace
} else {
    // something
}
karim79