简体   繁体   中英

Stop form submitting in jquery if an error

This is my code: http://jsfiddle.net/Xk38X/6/

  $('#register').click(function()
{
    if( $('#company_f').val().length == 0 ) {
        $('#company_f').css("border", "solid 1px red");
    }
});

The issue is even when it errors it still sends the form. Can anyone please tell me how I stop it submitting the form if the user hits the button and the company field isn't filled out.

Thank you.

Use return false or event.preventdefault()

$('#register').click(function (e) {
    if ($('#company_f').val().length == 0) {
        $('#company_f').css("border", "solid 1px red");
        return false; // or e.preventdefault();
    }
});


A Little better version of your code

 var company_f = $('#company_f'); //cache your selector $('#register').click(function (e) { if (company_f.val().length == 0) { company_f.css("border", "solid 1px red"); return false; // or e.preventdefault(); } }); 

Also Read HTML required attribute

Here is my way:

 $('#register').click(function(event)
   {
if( $('#company_f').val().length == 0 ) {
    event.preventDefault();
    $('#company_f').css("border", "solid 1px red");

    }
   });

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