i have a jsp page. now i want to fill some information here and click the submit button. but i need to check that the textbox are not empty. how to do?
+1
A:
Canonical without using frameworks with added trim prototype for older browsers
<html>
<head>
<script type="text/javascript">
if (!String.trim) {String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};}
function validate(theForm) { // passing the form object
var val = theForm.textField1.value;
if (val==null || val.trim()=="") {
alert('Please enter something');
theForm.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
</script>
</head>
<body>
<form onsubmit="return validate(this)">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
</body>
</html>
mplungjan
2010-08-17 12:57:12
A:
Hey DUDE,
Use this scrip, It will help you a lot. I have given few of the explanation with line of code.
<script Language="JavaScript">
<!--
function Blank_TextField_Validator()
{
// Check the value of the element named text_name from the form named text_form
if (text_form.text_name.value == "")
{
// If null display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
text_form.text_name.focus();
// return false to stop further processing
return (false);
}
// If text_name is not null continue processing
return (true);
}
-->
</script>
<form name="text_form" method="get" action="#"
onsubmit="return Blank_TextField_Validator()">
<input type="text" name="text_name" >
<input type="submit" value="Submit">
</form>
All the Best !!!
Rahul Patil
2010-08-17 13:56:40
1) Not all browsers will understand text_form - you should use document.text_form 2) pass the form to the function is far safer and simpler 3) what's with the "DUDE" ? Could be a DUDETTE
mplungjan
2010-08-18 06:12:12
A:
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<STYLE>
</STYLE>
<script>
function checkvalue() {
mystring=document.getElementById('myString').value;
if(!mystring.match(/\S/)){
alert ('Empty value is not allowed');
return false;
}else{
alert ("correct input");
return true;
}
}
</script>
</HEAD>
<BODY>
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
</BODY>
</HTML>
Meryl
2010-09-05 09:06:06