+ 1

Can onclick function take arguments?

For example, I have few buttons with same onclick function. Is able this function to take argument where is(in DOM) this button placed?

20th Jul 2017, 10:49 PM
Š˜Š»ŃŒŃ Š±Š°Š“Š°Š½ŠøŠ½
Š˜Š»ŃŒŃ Š±Š°Š“Š°Š½ŠøŠ½ - avatar
5 Answers
+ 6
You can pass "this" to set context, store data in the button's dataset (or query other attributes): https://code.sololearn.com/Wy0LUvUwBB22/?ref=app
21st Jul 2017, 2:17 AM
Kirk Schafer
Kirk Schafer - avatar
+ 4
I don't exactly know what you mean but you can have this in HTML: <button onclick="myFunc('Hi')">Click me</button> and this in JS: function myFunc(str) { // use 'str' here }
21st Jul 2017, 12:03 AM
The Coding Sloth
The Coding Sloth - avatar
+ 3
Yes, it can :) I'll leave you one of my codes as an example, it shows 4 buttons with the same onclick function and each of them has a different argument, something like this: [HTML] <button onclick="select('arg1')"> Btn1 </button> <button onclick="select('arg2')"> Btn 2 </button> [JavaScript] function select(arg) { alert(arg); } My code as a reference: https://code.sololearn.com/WmhO3USSGhR4/?ref=app
21st Jul 2017, 3:43 AM
Pao
Pao - avatar
+ 3
Ohh ok nice :) there's another way to accomplish that using the document.getElementsByClassName() but I won't explain it here because I think @Kirk's way is shorter and you can store more information for the buttons with the property he proposed. You could mark his "answer as best" so others can find it more easily too ;) šŸ˜Š
22nd Jul 2017, 6:55 AM
Pao
Pao - avatar
+ 2
Thanks everybody for helping me. Im not good in javascript yet, thats why I told my question not clearly. I wanted to make buttons with same onclick function that when I click button, it outputs its DOM location and I can to find out its color, id, etc. Kirk Schafer's answer helped me to resolve this problem
21st Jul 2017, 10:45 PM
Š˜Š»ŃŒŃ Š±Š°Š“Š°Š½ŠøŠ½
Š˜Š»ŃŒŃ Š±Š°Š“Š°Š½ŠøŠ½ - avatar