1

Having the following form:

<form id="my_form">
    <input type="submit" value="Save" id="my_form_save"/>
    <input type="submit" value="Save and apply" id="my_form_save_apply"/>
</form>

and the following jQuery code:

$('#my_form').submit(function(e) {
    e.preventDefault();
    var clicked_button = e.originalEvent.explicitOriginalTarget.id;
    console.log(clicked_button)
});

I would like to know how to detect which of the two buttons were clicked.

The code above throws this error: Uncaught TypeError: Cannot read property 'id' of undefined.

Also, I found out that e.originalEvent.explicitOriginalTarget.id doesn't work on all browsers so I need another solution.

2 Answers 2

2

What i suggest you is to change your code to use jquery to handle submit button click event. It will work on all browsers

var buttonClicked = "";
$('#my_form').submit(function(e) {
    e.preventDefault();
  alert(buttonClicked);
  buttonClicked=""; 
});
$("#my_form input[type = 'submit']").click(function(e){
 buttonClicked = $(this).attr("id");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><form id="my_form">
    <input type="submit" value="Save" id="my_form_save"/>
    <input type="submit" value="Save and apply" id="my_form_save_apply"/>
</form>

Sign up to request clarification or add additional context in comments.

Comments

2

As you already use jQuery I would suggest the following code:

$(document).on('click', 'input', function(e){
  e.preventDefault();
  var targetID = $(e.target).attr('id');
  if (targetID === 'my_form_save') {
    console.log('Save was clicked');
  } else if (targetID === 'my_form_save_apply') {
    console.log('Save and apply was clicked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form">
    <input type="submit" value="Save" id="my_form_save"/>
    <input type="submit" value="Save and apply" id="my_form_save_apply"/>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.