Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if text fields are empty on form submit using jQuery?

How could I use jQuery to check if text-fields are empty when submitting without loading login.php?

<form action="login.php" method="post">     <label>Login Name:</label>     <input type="text" name="email" id="log" />     <label>Password:</label>     <input type="password" name="password" id="pwd" />     <input type="submit" name="submit" value="Login" /> </form> 

Thanks.

like image 376
conmen Avatar asked May 15 '13 04:05

conmen


People also ask

How check text field is empty or not in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.


2 Answers

You can bind an event handler to the "submit" JavaScript event using jQuery .submit method and then get trimmed #log text field value and check if empty of not like:

$('form').submit(function () {      // Get the Login Name value and trim it     var name = $.trim($('#log').val());      // Check if empty of not     if (name  === '') {         alert('Text-field is empty.');         return false;     } }); 

FIDDLE DEMO

like image 93
palaѕн Avatar answered Sep 23 '22 05:09

palaѕн


You can use 'required' http://jsbin.com/atefuq/1/edit

<form action="login.php" method="post">     <label>Login Name:</label>     <input required type="text" name="email" id="log" />     <label>Password:</label>     <input required type="password" name="password" id="pwd" />     <input  required type="submit" name="submit" value="Login" /> </form> 
like image 26
NEO Avatar answered Sep 23 '22 05:09

NEO