0

I have some Javascript, and in one function, I need to get the id of the button that was just clicked. I tried a few things, like this:

var e = window.event,
btn = e.target || e.srcElement;
alert(btn.id);

but that just causes my program to crash.

And this:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}

that also just causes my program to crash.

And this:

function functionName(clicked_id) {
    alert(clicked_id);
}

that just alerts "undefined".

If I could have some debugging help or just another way to do it, that would be helpful, but it can't have jquery.

Thanks

CPC
  • 163
  • 5
  • 17
  • 1
    possible duplicate of [JavaScript - onClick to get the ID of the clicked button](http://stackoverflow.com/questions/4825295/javascript-onclick-to-get-the-id-of-the-clicked-button) – Xyzk Feb 02 '14 at 23:05
  • bjb568, what do you mean? maybe I used the wrong word but what I meant was that none of the program works. – CPC Feb 02 '14 at 23:07
  • From the duplicate answer: http://jsfiddle.net/TKKBV/2/ – Wiktor Zychla Feb 02 '14 at 23:07

4 Answers4

2

If you're using addEventListener(), then this will point to the DOM object that originated the event and this.id will be that object's id value.

var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function(e) {
        alert(this.id);
    });
}

Working demo: http://jsfiddle.net/jfriend00/7frQ5/

You also need to change your for loop end condition to just <, not <= because you were going off the end of the array.


If you need support for browsers older than IE 9, you can use this cross browser event function:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}

var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
    addEvent(buttons[i], "click", function(e) {
        alert(this.id);
    });
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Can you explain what each part is doing? – CPC Feb 02 '14 at 23:14
  • @CPC - I simplified the code (edits made by someone besides me that seemed overly complicated). Let me know what you need explained if you still need help. – jfriend00 Feb 02 '14 at 23:39
  • That second one worked, but I just have one more question, how do I assign that value to a variable instead of alerting it? – CPC Feb 03 '14 at 17:40
  • @CPC - `var x = this.id`. Not sure what you're really asking. – jfriend00 Feb 03 '14 at 17:44
  • @CPC - Assigning it to a variable absolutely DOES work. So something else you are doing with the id or that variable is not right. You'd have to show us what code that is for further help. – jfriend00 Feb 03 '14 at 17:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46696/discussion-between-cpc-and-jfriend00) – CPC Feb 03 '14 at 17:59
  • Many thanks @Jfriend00. How about that if i want use the id in another function, how can i get that id in a form something like textcontext instead of using the alerting function? Thanks. – Eric May 30 '22 at 07:12
1

In your for loop the value of i should be < than the length not <=...

try this:

for (var i = 0; i < buttonsCount; i++) {

Example

Apart from that your code works good:

var buttons = document.getElementsByTagName("button"); // target all buttons into a element array/collection
var buttonsCount = buttons.length; // cache the length
for (var i = 0; i < buttonsCount; i++) { // reset the counter; check if its smaller than the array length; add itself
    buttons[i].onclick = function(e) { // assign a function to the onclick event
        alert(this.id); // alert the id attribute of the element clicked 
    };
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sergio
  • 28,539
  • 11
  • 85
  • 132
0
function testClick(id){
  alert(id);
}

<a href="javascript:void(0);" id="test" onclick="testClick(id)"> Click</a>
uihelp
  • 198
  • 2
  • 7
0

Looking at the first attempt you have made I believe you can do something along the lines of:

Say for an example you have the following html

<div id="testId" onClick ="doStuff(event)"> click me </div>

You can get the id attribute of the element where the onclick event originated within the "doStuff":

function doStuff(event){
    event = event || window.event; 
    var element = event.target || event.srcElement; 
    if (element.nodeType == 3){
       element = element.parentNode;
    }
    var id = element.id;
    alert(id);//This will contain the value of the id attribute of the above DIV element, "testId"
}

Note: that the window.event and event.srcElement are Microsoft's implementation of accessing the last event that took place, and the element where this event was triggered from respectively.

And the if statement to check the node type is there to prevent a certain issue that can occur with safari, that is: if the event took place in a element that contains text, then this text node becomes the element where this event took place, so to workaround this we can check the node type, and if it is a text node we fall back to its parent node.

You can learn more about events by following this link: http://www.quirksmode.org/js/events_properties.html

This is a good reference to available node types: Node Types

Hope this helps to clarify the issues you are having.

TDR
  • 1