开发者

Submitting form by hitting enter on keyboard

开发者 https://www.devze.com 2023-02-22 21:09 出处:网络
Currently my team has this (onKeyPress=\"keyPress(event)) defined for each field in a form. So if i have 20 fields then it is defined 20 times. I am wondering if it is possible to define this at the f

Currently my team has this (onKeyPress="keyPress(event)) defined for each field in a form. So if i have 20 fields then it is defined 20 times. I am wondering if it is possible to define this at the form level rather than field so we only define it one and not 20 ti开发者_如何学Pythonmes?

Using PHP codeignitor.


Define the event for the whole <form>. Then use event.target to find a particular form element and do something with it.

  • A form element key-press event is generated and passed to the <form> element for handling.
  • No handler is directly bound to the element, so the event bubbles up the DOM tree to the <form>.
  • Here you test if the event.target matches the said element.
  • If a matching element is found, the <form> handler is called on it


If you have jquery, you can bind it to all the input fields at once...

$('input').bind('keypress', function (e) { 
        if (e.keyCode == 13) {
            //do stuff
        }
});


Let's think your form is like below

<form id="my_form" method="post">
    [...]
</form>

Then you can submit with JS like this:

<script>
    $(document).on("keypress", function(e) {
        if(e.which == 13) {
           $('#my_form').submit();
        }
    });
</script>
0

精彩评论

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