+ 2

Please guys help me in JavaScript:

If there is three button i have declared with different names then i call a function by button 1 then how if put it into the condition that what button is called. My this condition is not working : if(document.getElementsByTagName("button").name.b1.selected == true) can you guys solve my this problem.

27th Mar 2018, 1:22 PM
Praveen Soni
Praveen Soni - avatar
2 Answers
+ 5
You can get attributes using getAttribute(). Notice that you have 3 buttons so you will return get an array. var name = document.getElementsByTagName("button")[0].getAttribute["name"]; //button 1 var name2 = document.getElementsByTagName("button")[1].getAttribute["name"]; //button 2 .selected doesn't make sense when using buttons. It's used with <option> tags not buttons.
27th Mar 2018, 2:21 PM
Toni Isotalo
Toni Isotalo - avatar
+ 3
To maximize your chances to be helped, link the code related to your question... I guess you're talking about this one: https://code.sololearn.com/W0AQU26G550L/?ref=app To answer your question, by defining event listeners of your buttons ('onclick' attribute) in the html source code, you should add an argument in your function call and definition, to pass a reference to it... Simplest way would be to explicitly pass the button name : <button onclick="func('b1')">button 1</button> func(btn) { if (btn == "b1") { /* do something specifically for button 1 */ } // do anything else, maybe other tests for specific task for others buttons } ... but you could access button attributes a little more implicitly through the use of the "this" special keyword: <button onclick="func(this.name)" name="b1">button 1</button> /* same func(btn) definition than previously */ ... as well as pass directly the "this" reference to use it in your function: <button onclick="func(this)" name="b1">button 1</button> func(btn) { if (btn.name == "b1") { /* do something specifically for button 1 */ } // do anything else, maybe other tests for specific task for others buttons }
27th Mar 2018, 3:23 PM
visph
visph - avatar