开发者

Submitting a form with the enter button in a form with several submit buttons

开发者 https://www.devze.com 2023-01-22 16:37 出处:网络
I have a form with a simple text field and multiple submit buttons. When the user presses enter, I want to submit the form with a specific submit button, but it looks like the form just chooses the fi

I have a form with a simple text field and multiple submit buttons. When the user presses enter, I want to submit the form with a specific submit button, but it looks like the form just chooses the first button开发者_如何学JAVA instead. Is there any way to tell the browser which submit button to choose when user presses enter? Preferrably without javascript, but I'll take it if that's the only solution.

Edit: I have no other choice than having multiple submit buttons. This is a legacy app.


There's no way. The simplest solution is just to ensure that the first submit button in the form is the one you want triggered by the Enter button.

Note that this submit button can be a duplicate of a button elsewhere in the form, and it doesn't have to be visible.


You can use simple JS to catch the onkeypress event:

onkeypress="if ((event.keyCode | event.which) == 13) { document.getElementById('MySubmitButton').click(); return false; }"

Just add this to the textbox tag and replace "MySubmitButton" with the ID of the desired submit button.

Note: use ID, not name.


If you had the following HTML

<form id="form_one">
    <input type="submit" value="Submit 1" />
</form>
<form id="form_two">
    <input type="submit" value="Submit 2" />
</form>

Then you could have a bit of jQuery as follows

$(document).ready(function() {
    $(this).keydown(function(e) {
        if (e.keyCode == '13') {
            $("#form_one").submit();
        }
    });
});

Obviously you'd have to put in the logic to decide which form to submit.

Also as far as I know if a control in "form_one" had focus and you hit enter it would automatically submit that form the control is contained within.


you can just define a javascript method on the "onclick" or "onkeypress" event of the button, from which u wanted to get the form submitted. But u have to define the process to occur in the javascript function

0

精彩评论

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

关注公众号