Search code examples
jqueryformseventssubmitpreventdefault

Prevent form submit if field value is false


I am trying to create some code to use jQuery to prevents the users from submitting a form if the value in a text field is different from 50. The form submit work great, but I am having some issues with the jQuery code to prevent submitting.

My HTML Code:

<form name="vehicleRegFrm" id="vehicleRegFrm" action="" method="post">
    <input name="samp" id="samp" type="text" />
    <input name="sbtAddCarFrm" type="submit" value="Continue" />
</form>

Here is the problematic jQuery code:

$('sbtAddCarFrm').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;

    if ($('samp').val() != 50) {
        $('vehicleRegFrm').submit();
    } else {
        alert("your message");
    }
});

Solution

  • try this

      $("#vehicleRegFrm").submit(function(){
             if ($('#samp').val() != 50) {
                 alert('form will not be sent')
                 return false;
             }
             else {
                 alert('form will be sent')
                 return true;
             }
      })
    

    if the user write 50 the form will be sent if the user write a different value nothing will be sent