I want to check a textarea whether it is empty or not. For this I write the following code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value ie, it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?
I am getting it correctly. This is what I did.
Please Write Problem Description
. Please Write Problem Description
. Note: Use a trim
function to eliminate empty spaces.
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Do check for white space in the value like this
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute.
function validateForm(theForm) { var problem_desc = document.getElementById("problem_desc"); if (problem_desc.value.replace(/ /g,'').length) { return true; } else { alert("Please Write Problem Description"); return false; } }
<textarea id="problem_desc"></textarea> <button onclick="validateForm()">Validate</button>
我会说你更好修剪,然后检查空格的长度。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.