开发者

How to check whether the input text field contains only white spaces?

开发者 https://www.devze.com 2022-12-27 20:05 出处:网络
What is the easiest way to check in Javascript whether the input text field is empty (开发者_运维问答contains nothing or white spaces only)?var str = document.getElementById(\"myInput\").value;

What is the easiest way to check in Javascript whether the input text field is empty (开发者_运维问答contains nothing or white spaces only)?


var str = document.getElementById("myInput").value;
if (str.match(/^\s*$/)) {
    // nothing, or nothing but whitespace
} else {
    // something
}


You are looking for something like trim function, right?


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消