简体   繁体   中英

detect the submit event when click enter key

If I have one form with actually different inputs for two submit requests. When I click on any submit button I can know what action to do. but I need to detect in which input I'm when click Enter keyboard key.

<form class="main-form">
  <div class="form_one">
    <input class="form_one_input" type="text" id="form_one_input"/>
    <button type="submit" class="form_one_button">Submit form one</button>
  </div>
  <div class="form_two">
    <input class="form_two_input" type="text" id="form_two_input"/>
    <button type="submit" class="form_two_button">Submit form two</button>
  </div>
</form>

https://jsfiddle.net/m6433obp/

To detect which input you are in use the keyup event handler as:

$('.form_one').bind('keyup', function(e) {
    if(e.keyCode === 13) {
    alert($(this).attr('class'));
  }
})
$('.form_two').bind('keyup', function(e) {
    if(e.keyCode === 13) {
    alert($(this).attr('class'));
  }
})

check demo for this here

I am not really sure that I understand your question correctly. But I think that since you are using two submit buttons in the same form, you should give unique names to the buttons, so that on the server side you know that on hitting enter which input got submitted.

<form class="main-form">
  <div class="form_one">
    <input class="form_one_input" type="text" id="form_one_input"/>
    <button type="submit" name="first_button" class="form_one_button">Submit form one</button>
  </div>
  <div class="form_two">
    <input class="form_two_input" type="text" id="form_two_input"/>
    <button type="submit" name="second_button" class="form_two_button">Submit form two</button>
  </div>
</form>

And the code to check:

 if (isset($_POST['first_button'])) {

    } else if (isset($_POST['second_button'])) {

    } else {        
       //no button pressed
}

Hope this is what you were looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM