Reputation: 15408
I have a form that has a bunch of regular fields, and basically what is a sub-form (although it doesn't have another form tag) which sets up hidden fields via javascript. However, if you hit enter to submit the sub-form, it submits the larger form. I understand why it does this, but it is not the desired behavior.
Is there a simple way to set up a sub-form in javascript so that when its submitted (enter button, button click, etc.) a java event handler is called?
I'm trying to avoid checking for specific keypressed events. I would much prefer to preserve native browser submission controls.
Upvotes: 0
Views: 46
Reputation: 1
Attach a keypress event handler to a DIV tag that wraps your sub form. In the handler, check the key code property of the event object. If it is 13 then the user pressed the enter key, and then you can "submit" the sub form.
div.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
// submit sub form
}
});
Upvotes: 0
Reputation: 7416
What you could do is, instead of having a <input type="submit"/>
, you could have an <input type="button" onclick="handle()"/>
, and then, in your handle()
function, you could loop through the child elements of the div
you have the sub-form elements in. <input type="submit"/>
is designed to submit the entire form; it doesn't know that you're in a subform. Also, as far as I know, HTML doesn't allow nested form tags without hackish code.
I don't think you're going to be able to do what you want to do, which is nested forms, including an event handler, without bypassing the spec. I think the best thing to do is to just put them in a div, attach a keydown handler, and then loop through the form elements with childNodes
Upvotes: 0
Reputation: 23250
You're using the jQuery tag, so I'll give you a jQuery solution:
<form id="innerForm">
<!-- Form Stuff -->
</form>
<script>
$('#innerForm').submit( function(e) {
// called when the submit button is pressed
});
</script>
The submit handler will be called however the form is submitted. If you want to stop the page from being refreshed then add the line e.preventDefault()
in the handler.
Upvotes: 1