Prevent form submission with empty input field

when no value is specified in the "roll" input field, a warning is generated by the "empty ()" function, but this empty value is still passed to "retrive.php", so how to stop it and just go through value to 'retrive'. php when some input value is provided.

<html> <head> <title>STUDENT FORM</title> <script type="text/javascript"> function empty() { var x; x = document.getElementById("roll-input").value; if (x == "") { alert("Enter a Valid Roll Number"); }; } </script> </head> <body > <h1 align="center">student details</h1> <div id="input"> <form action='retrive.php' method='get'> <fieldset> <legend>Get Details</legend> <dl> <dt><label for="roll-input">Enter Roll Number</label></dt> <dd><input type="text" name="roll" id="roll-input"><dd> <input type="submit" value="submit" onClick="empty()" /> </dl> </fieldset> </form> </div> </body> </html> 
+8
javascript
source share
5 answers

You need to return false to cancel sending.

 function empty() { var x; x = document.getElementById("roll-input").value; if (x == "") { alert("Enter a Valid Roll Number"); return false; }; } 

and

 <input type="submit" value="submit" onClick="return empty()" /> 

JsFiddle example

+22
source share
 <form method="post" name="loginForm" id ="loginForm" action="login.php"> <input type="text" name="uid" id="uid" /> <input type="password" name="pass" id="pass" /> <input type="submit" class="button" value="Log In"/> <script type="text/javascript"> $('#loginForm').submit(function() { if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") { alert('Please enter Username and Password.'); return false; } }); </script> </form> 
+3
source share

I use it, I think it can help

  $(function () { $('form').submit(function () { if ($('input').val() === "") { alert('Please enter Username and Password.'); return false; } }); }) 

or work with a class or identifier like this

 $('.inputClass') $('#inputID') 
+2
source share

Make empty() return false if the form should not be submitted

+1
source share

If you want to save the code, you can simply do:

 <input type="text" name="roll" id="roll-input"> <input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/> 

I'm just saying.

0
source share

All Articles