Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which button is clicked

In my page I have many edit buttons each name starts with "edit" and then some id. I want to know any of my edit buttons is clicked or not. In details, I have form. In form I have many edit buttons which name starts with "edit" , delete buttons which name starts with "delete" and 1 add button. All are submit buttons. form onsubmit I call JavaScript function in which I want if the button is edit confirm("some text") else submit form. How can I do that in JavaScript? I think give all these buttons same id and then getElementById but then how con I change?

like image 772
Aram Gevorgyan Avatar asked May 05 '11 10:05

Aram Gevorgyan


1 Answers

This is simple using jQuery:

$(':button').click(function() {
  // reference clicked button via: $(this)
  var buttonElementId = $(this).attr('id');
});

Try it out: http://jsfiddle.net/7YEay/

UPDATE based on feedback in comments

This is untested/pseudo code:

$(':submit').click(function(event) {
  var buttonName = $(this).attr('name');

  if (buttonName.indexOf('edit') >= 0) {
    //confirm("some text") logic...
  }

  event.preventDefault();
});

This documentation may be helpful too: http://api.jquery.com/submit/

like image 198
Kon Avatar answered Sep 27 '22 18:09

Kon