How to find out which button is pressed

There are many edit buttons on my page, each name starts with "edit" and then with id. I want to know if any of my edit buttons are pressed or not. In detail, I have a form. In the form, I have many edit buttons, the name of which begins with "edit", delete buttons, the name of which begins with "delete" and 1 add button. All buttons represent. form onsubmit I call a JavaScript function in which I want if the button is an edit confirmation ("some text") else submit form. How can i do this in javascript? I think all of these buttons use the same identifiers and then getElementById, but then how can I change?

+4
source share
5 answers

It is simple using jQuery:

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

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

UPDATE based on reviews in comments

This is unverified / 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 also be useful: http://api.jquery.com/submit/

+5
source
 function MyOnSubmit(e){ e = e || window.event; // srcElement for IE, target for w3c var target = e.target || e.srcElement; if (target.id.indexOf("edit") > -1){ // an edit button fired the submit event } } 

although I advise you to continue your research to find the best way to handle the edit and delete buttons (for example, link them with href = editpage.jsp? id = 23)

+2
source

I'm sure you just answered it yourself ...

Each one begins with β€œediting” and ends with a unique identifier? So ... $ (button) .attr ("id") will give you this. Store it in a variable? Not sure what you are trying to do.

+1
source

bind click event for all buttons:

 for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; if (button.addEventListener) { button.addEventListener('click', handler, false); } else { button.attachEvent('onclick', handler); } } 

in the event handler, get the Event object, and then get the target:

 function handler(e) { e = e || window.event; // srcElement for IE, target for w3c var target = e.target || e.srcElement; var id = target.name.substring(4); /* your code rely on id */ } 
+1
source

I think that you may have incorrectly formulated your question. If you use jquery, placing a button is as easy as $('#id') , and if you want to store any information on that button, you can either add an attribute or use the jquery.data function.

 $('#id').attr("pressed", "true"); 

or

 $('#id').data('pressed', 'true'); 
+1
source