Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the button value into my onclick event function?

Tags:

javascript

<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 ?

like image 423
showkey Avatar asked Oct 19 '16 14:10

showkey


People also ask

How do I get the value of a button clicked?

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.

How do you pass parameters on Onclick react?

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 .

Can I get value from Button JavaScript?

Use the value property to get the value of a button in JavaScript.

How do you handle button click events?

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.


3 Answers

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); } 
like image 188
Clyde Lobo Avatar answered Sep 18 '22 16:09

Clyde Lobo


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>
like image 38
runit Avatar answered Sep 16 '22 16:09

runit


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);
}
like image 42
Deividas Karzinauskas Avatar answered Sep 19 '22 16:09

Deividas Karzinauskas