12

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

3 Answers 3

11
var str = document.getElementById("myInput").value;
if (str.match(/^\s*$/)) {
    // nothing, or nothing but whitespace
} else {
    // something
}
Sign up to request clarification or add additional context in comments.

Comments

4

You are looking for something like trim function, right?

4 Comments

Yes, thanks ! Actually jQuery has a built-in trim() function !
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. docs.jquery.com/Plugins/Validation/blank
+1 You are right. I should have mentioned that. Thanks for the :blank !
the link is broken now, and with current strategy, the answer is more like a link only answer
1

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.