开发者

How to check before submit?

I need to check if the user clicked on a button before I preform the submit.

Right now, I a开发者_JS百科m using $(document).ready(function(){ and I want to put in it, the code to check if the button was pressed or not.

This "button" its just a simple div, with background image that changes the image if you click there. So I need to add a variable so I can make an if statement, right?

I know there is preventDefault function in JQ, but tried with no success to work with it.

thanks for help


jQuery('#yourForm').bind('submit',function(e){

    //do your test
    //if fails 
    e.preventDefault();

});


Does this answer your question ?

$(document).ready(function(){
    $('#yourDiv').click(function() {
        $('#yourForm').submit();
    });
});

I have added a click handler on the "button div". When it is clicked it submits the form. So you don't have to have a submit button in your form, just your div button


$('#form_element').submit(function() {
    return false;  // do this if you don't want to submit the form
});

You can add as much submit events as you want. The form will not be submitted if one or more submit events return false;


Add another input element which stores whether the button is clicked

<div id="divElement">
<input type="hidden" name="buttonIsClicked" value="0" />
</div>

and set the event handler for the div.

$("#divElement").click( function() {
  $(this).children("input[name=buttonIsClicked]").val(1);
});

Adding the input element inside the div makes the code execute faster since it just has to search only under the div element and not the entire DOM. If you want to place the input element outside, then too you could make your code optimized by using

$(this).parent().find("input[type=buttonIsClicked]");

on form submission you could check this by

$(myFormElement).submit(function() {
  if($(this).find("input[name=buttonIsClicked]").val() == 0)
    return false;
  //proceed here if the button div is clicked
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜