Reputation: 1639
I want to check whether a text box contains a name or not. If not then an alert should be popped up displaying a message after pressing a submit button and the page should not submit the blank value. If it contains value then the value should be submitted.
I am using the below code. When I leave the text box empty and click the submit button, it displays the alert as expected, but it also submits the empty value after dismissing the alert.
<html>
<head>
<script type="text/javascript">
function check()
{
if (!frm1.FileName.value)
{
alert ("Please Enter a File Name");
return (false);
}
return (true);
}
</script>
</head>
<body>
<form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
<input type="text" name="FileName" id="FileName">
<input type="submit" value="send" name="btn_move" id="btn_move" onclick="check()">
</form>
</body>
</html>
What is the problem in the code?
Upvotes: 2
Views: 65947
Reputation: 816374
You return false
from the check
, but you are not returning the value from the event handler.
Only if the event handler returns false
, the default action (submitting the form in this case) is prevented:
onclick="return check();"
Have a look at the great introduction to event handlers at quirksmode.org to learn the basics about event handling (and to learn about better ways than inline event handlers).
In general it is better to perform these checks not when the submit button is pressed but just before the form is submitted. So, instead of binding the handler to the click event on the button, bind it to the submit event of the form, for example (using traditional event handlers):
document.getElementById('frm1').onsubmit = function() {
if (!this.FileName.value) {
alert ("Please Enter a File Name");
return false;
}
};
The advantage is that the check will be done for all form submissions, not only when the submit button is clicked (for example if the submit button is "executed" by pressing the enter key).
Upvotes: 1
Reputation: 15387
Try this
<html>
<head>
<script type="text/javascript">
function check()
{
if (document.getElementById('FileName').value==""
|| document.getElementById('FileName').value==undefined)
{
alert ("Please Enter a File Name");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
<input type="text" name="FileName" id="FileName">
<input type="submit" value="send" name="btn_move" id="btn_move" onclick="return check();">
</form>
</body>
</html>
Upvotes: 4