jQuery form submit: Any way to know what element t

2019-06-25 09:45发布

I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel"). Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

4条回答
Deceive 欺骗
2楼-- · 2019-06-25 09:53

EDIT

This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.


@Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:

$('form').submit(function(e){
    if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
        //don't validate
    }
    else{
        //validate
    }
});
查看更多
放我归山
3楼-- · 2019-06-25 09:54
var myForm =   $('form');
$('input[type="submit"]',myForm).click(function(e) {
    var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
    //do other things here
});

EDIT

.submit(function(event){
    var target = event.originalEvent.explicitOriginalTarget.value;
    //But IE does not have the "explicitOriginalTarget" property
});
查看更多
4楼-- · 2019-06-25 10:00

I asked this same question: How can I get the button that caused the submit from the form submit event?

The only cross-browser solution I could come up with was this:

$(document).ready(function() {
    $("form").submit(function() { 

    var val = $("input[type=submit][clicked=true]").val()

    // DO WORK

});

$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.

查看更多
ら.Afraid
5楼-- · 2019-06-25 10:01

well this will only fire if the type of the input button is like so:

<input type='submit' ...

so make sure the cancel button does not have type='submit' and it should work

查看更多
登录 后发表回答