0

I have created this function in JQuery:

function CheckRequired() {
    var ret = true;

    $(".required").each( function() {
        var check = $(this).val();

        if(check == '') {
            //alert($(this).attr("id"));
            ret = false;
        }
    });

    if(!ret) {
        alert("One or more fields cannot be blank");
        return false;
    }
}

on my forms submit buttons, i run this onClick

<input type="submit" onClick="CheckRequired();" />

if any fields in the form with a class of required have a blank value the error will alert to the user and the form should not submit.

the alert is showing, however the form still seems to be submitting

Charles
  • 179
  • 6
  • 19

3 Answers3

1

use preventDefault. This method makes sure the default action of the event will not be triggered.

function CheckRequired(event) {
var ret = true;

$(".required").each( function() {
    var check = $(this).val();

    if(check == '') {
        //alert($(this).attr("id"));
        event.preventDefault();
    }
});

if(!ret) {
    alert("One or more fields cannot be blank");
    event.preventDefault();
}

}

maxspan
  • 13,326
  • 15
  • 75
  • 104
  • `return false` does the same, but when event handler will be linked to button rather than form, it will prevent button's behavior and won't let form be submitted unless you do that yourself from javascript – paulitto Feb 11 '15 at 01:31
0

To prevent form from submission you should bind event to form's onsubmit, and return function result

<form onsubmit="return CheckRequired()" />

Also, as you already use jquery it would be much more convenient to bind events in javascript:

$('#form_id').submit(function(){
  //your form submit code
})
paulitto
  • 4,585
  • 2
  • 22
  • 28
0

I think you have to prevent the default submission action by using event.preventDefault(); as noted here: Prevent submit button with onclick event from submitting

Community
  • 1
  • 1
RamRovi
  • 986
  • 9
  • 13