问题
i hava a form with a hidden submit button and one text input. In the text input, with jQuery i attached to it a change event that submits the form. The thing is that if i hit enter on the input, then the form submits twice. I think is because the enter submits the form and the input detects a change event and it submit the form again. I have two questions: - Is my thought right? - How can i fix this?
This is the javascript:
$("input.price").live('change', function () {
$(this).closest('form').submit();
});
Edit: I think that the e.preventDefault() is preventing the default of the event "change" but no preventing the event "submit".. i try this before the event "change" with no luck but maybe im close to the solution:
$("input.price").live('submit', function (e) {
e.preventDefault();
});
回答1:
$("input.price").live('change', function (eventObject) {
eventObject.preventDefault();
$(this).closest('form').find('input.submitButton').click();
});
回答2:
You need to use the preventDefault() function to prevent the form from submitting.
E.g.
$("input.price").live('change', function (e) {
e.preventDefault();
$(this).closest('form').find('input.submitButton').click();
});
回答3:
What am i missing here, why wouldn't you do this instead:
$("input.price").live('change', function (eventObject) {
$(this).closest('form').submit();
});
回答4:
Finally i came out with a solution! The thing was that.. as Mike C. says, the extra code could help to solve the problem. The problem was that the form that i'm trying to submit it's an Ajax.BeginForm of MVC so.. the main problem is the ajax submit of that form, that was the second submit!
I couldn't change that behavior.. only changing the Ajax.Beginform with a Html.Beginform.. thing that i don't want to do. So.. i came out with this "rusty" solution:
$("input.price").live('keypress', function (e) {
if (e.keyCode == 13) {
$(this).attr('data-submitting', true);
}
});
$("input.price").live('change', function (e) {
if (!$(this).attr('data-submitting')) {
$(this).closest('form').submit();
}
});
来源:https://stackoverflow.com/questions/15371791/prevent-submit-form-twice-with-change-event