here is the code sample: HTML:
<form id="information" name="information" action="#" method="post">
<textarea name="text" rows="10" cols="10">
</textarea>
<input type="submit" valu开发者_运维知识库e="submit"/>
</form>
Javascript:
window.onload=init;
function init(){
document.getElementById('information').onsubmit=validateForm;
}
function validateForm(){
var text= document.information.text.value;
if(text==""){
alert('text area cannot be empty');
return false;
}
}
it does not work...
You've got a carriage return in your textarea - so its value is \n
or \r\n
close your tag on the same line
Edit:
You could strip the beginning and end whitespace using this function
function trim( str ) {
return str.replace( /^\s+|\s+$/g, '' );
}
The textarea has a carriage return in it (and a space), so your condition is never true. So change it to:
<textarea name="text" rows="10" cols="10"></textarea>
However you may want to go further and stop the user entering an "empty" response (meaning nothing but white-space). Or you may just want to remove leading and trailing white-space. If so you can do this:
text = text.trim();
Now trim()
I believe is relatively new (Firefox lists it as new in 3.5). A more backwards compatible version is:
text = text..replace(/^\s\s*/, '').replace(/\s\s*$/, '');
and then testing if it's empty.
Faster JavaScript Trim has a good analysis on various white-space trimming alternatives. For instance the above can be done with one regex:
text = text..replace(/^\s+|\s+$/g, '');
but
This commonly thought up approach is easily the most frequently used in JavaScript libraries today. It is generally the fastest implementation of the bunch only when working with short strings which don't include leading or trailing whitespace. This minor advantage is due in part to the initial-character discrimination optimization it triggers. While this is a relatively decent performer, it's slower than the three methods above when working with longer strings, because the top-level alternation prevents a number of optimizations which could otherwise kick in.
This worked for me:
function validateForm(){
var text = document.information.text.value;
if(text == " \n "){
alert("Error");
return false;
}
}
精彩评论