<input type="button" value="mybutton1" onclick="dosomething()">test
The dosomething function evoked when to click the button,how can pass the value of the button mybutton1
into dosomething function as it's parameter ?
Get Clicked Button ID With the Event.target.id Method in JavaScript. You can get a button ID during a click event thanks to the target property of the Event interface. The target property refers to the button element that got the click event from the user.
To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .
Use the value property to get the value of a button in JavaScript.
Onclick in XML layout When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.
You can pass the value to the function using this.value
, where this
points to the button
<input type="button" value="mybutton1" onclick="dosomething(this.value)">
And then access that value in the function
function dosomething(val){ console.log(val); }
Maybe you can take a look at closure in JavaScript. Here is a working solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<p class="button">Button 0</p>
<p class="button">Button 1</p>
<p class="button">Button 2</p>
<script>
var buttons = document.getElementsByClassName('button');
for (var i=0 ; i < buttons.length ; i++){
(function(index){
buttons[index].onclick = function(){
alert("I am button " + index);
};
})(i)
}
</script>
</body>
</html>
You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test
by passing this. Then in the function you can access the value like this:
function dosomething(element) {
console.log(element.value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With