user3003810
user3003810

Reputation: 961

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/

Upvotes: 0

Views: 715

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281686

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

Upvotes: 1

Jagrati
Jagrati

Reputation: 12222

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.

Upvotes: 0

Related Questions