We're trying to make a generic approach for a piece of software we are developing that ties into form fields.
So far so good but we're running in to an edge case that prevents submitting a form/field that has another handler tied in to it.
Here's the (condensed) use case:
HTML:
<form id="form1">
<input type=field id="field1"/>
</form>
<a href="#" id="link">click to submit</a>
Normal behaviour is that when a user types 'foo' into the field and hits enter, the form is handled and submitted to the correct 'endpoint' which isn't necessarily the defined one in the form's opening tag. There could be some function (from somewhere else) that handles this enter-event.
Unfortunately, we can't predict what that function is, we like to keep it generic.
In the above HTML, clicking on the link should trigger an enter-event on the form field that mimics the browser/user behaviour and thus some unknown handler.
This is our Javscript (we're using jquery):
$('#field1').keypress(function (event) {
if (event.which == 13) {
console.log("enter pressed");
//return false; only if needed
}
});
$( "#link" ).click(function() {
var e = jQuery.Event('keypress');
e.which = 13; // #13 = Enter key
$("#field1").focus();
$("#field1").trigger(e);
})
When entering 'foo' in the field and pressing enter the form gets submitted. But when we click the link we do a focus() and then firing the key-event but the form isn't submitted.
We can't use a submit() because of the unknown handlers.
Try the code here: http://codepen.io/conversify/pen/yOjQob
What happens when enter key is pressed is, if the input is inside a form, the form is submitted. This is the default behavior. When you simulate a key press, you should do the same, unless the default behavior is prevented.
$('#field1').keypress(function (event) {
if (event.which == 13) {
console.log("enter pressed");
// event.preventDefault(); if needed
}
});
$( "#link" ).click(function() {
var e = jQuery.Event('keypress');
e.which = 13; // #13 = Enter key
$("#field1").focus();
$("#field1").trigger(e);
var form=$("#field1").closest("form");
if(form&&!e.isDefaultPrevented()) form.submit();
})
Now you can pass your event object to the handlers and they can prevent the submit if they want so, or you can prevent it in your keypress handler.
You should separate out the form handler from the enter and click handlers.
var formHandler = function(e) {
// ... code to submit form ...
console.log("form handled");
};
Then set your keypress
handler like this:
$('#field1').keypress(function (event) {
if (event.which == 13) {
formHandler();
}
});
And your click handler like this:
$( "#link" ).click(function() {
formHandler();
});
You can unbind the unknown handlers using unbind('submit')
and then use submit()
like following.
$("#link").click(function () {
$("#form1").unbind('submit').submit();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With