+ 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?
5 ответов
+ 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
+ 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
}
+ 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
+ 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 ;) 😊
+ 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