简体   繁体   中英

Jquery empty field validation

when i submit the form with empty fields i get the success message in the dialog box. Instead i want to show error message in the dialog box. Please help me to find the solution.

My html code:

<form id="booking" action="" method="post">
  First Name:<input type="text" id="firstName" name="firstName" maxlength="30" /><br/>
  Last Name:<input type="text" id="lastName" name="lastName" maxlength="30"/><br/>
  Contact:<input type="text" id="contact" name="contact" maxlength="15"/><br/>
  Email: <input type="text" id="email" name="email" maxlength="30"/><br/>
  <input id="save" type="button" value="Save" />
  </form>
  <div id="dialog"></div>

Jquery code:

 $('#save').click(function(){
    if(('#firstName').length==0 && ('#lastName').length==0 && ('#contact').length==0 &&   ('#email').length==0){
     $('#dialog').attr('title','Error').text('All fields are required').dialog();
     }else{
     $('#dialog').attr('title','Success').text('Success').dialog();
     }
    });

('#firstName') -> if you are using jQuery this should be $('#firstName')

this conditions will always return false : ('#firstName').length==0 && ('#lastName').length==0 && ('#contact').length==0 && ('#email').length==0

to get the value length of a input type text:

$('#firstName).val().length

update:

try this:

$('#save').click(function(){
    if($('#firstName').val().length==0 && $('#lastName').val().length==0 && $('#contact').val().length==0 &&   $('#email').val().length==0){
     $('#dialog').text('All fields are required').dialog({title:'Error'});
    } else{
     $('#dialog').text('Success').dialog({title:'Success'});
    }
 });

Try this,

$('#save').click(function(){
    if($('#firstName').val()=="" || $('#lastName').val()=="" || $('#contact').val()=="" ||   $('#email').val()==""){
     $('#dialog').attr('title','Error').text('All fields are required').dialog();
     }else{
     $('#dialog').attr('title','Success').text('Success').dialog();
     }
    });

it should be OR in your if condition || and you can use [val()][1] to get the value of selected element and check if it is empty.

and you missed $ in your jquery selector

if(('#firstName').val()==""
---^--- //here missing $

try this

$('#save').click(function(){
  if($('#firstName').val()=='' || $('#lastName').val()=='' || $('#contact').val()=='' ||  $('#email').val==''){
     $('#dialog').attr('title','Error').text('All fields are required').dialog();
  }else{
    $('#dialog').attr('title','Success').text('Success').dialog();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM