JonnyQ
JonnyQ

Reputation: 1

Submitting form by hitting enter on keyboard

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 times?

Using PHP codeignitor.

Upvotes: 0

Views: 421

Answers (3)

Gihan Kaveendra
Gihan Kaveendra

Reputation: 19

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>

Upvotes: 0

two7s_clash
two7s_clash

Reputation: 5827

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

Upvotes: 2

Maxx
Maxx

Reputation: 4082

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
        }
});

Upvotes: 0

Related Questions