简体   繁体   中英

How do I get the clicked button name with getElemetByName?

I'm trying to get value of button which is clicked, or determine which button was clicked.

From code below, I'm getting all values but I just want the button that was clicked.

 <script type="text/javascript">
    function GetCheckedFruits () {
        var elements = document.getElementsByName ("fruit");
        for (var i=0; i < elements.length; i++) {
            if (elements[i].click) {
                alert ("The " + (i+1) + ". button is click");
            }
        }
    }
</script>

HTML:

<input id="Text1" name="fruit" type="button" value="apple" onclick="GetCheckedFruits ()" /><br />

<input id="Text1" name="fruit" type="button" value="banana" onclick="GetCheckedFruits ()" /><br />

<input id="Text1" name="fruit" type="button" value="blackberry" onclick="GetCheckedFruits ()" /><br />

Where am I going wrong?

change

if (elements[i].click) {
     alert ("The " + (i+1) + ". button is click");
}

to

if (elements[i].type == 'button') {
    alert ("The " + elements[i].value + " button is click");
}

thats it.

EDIT

Try this

function GetCheckedFruits (clickedButton) { alert ("The " + clickedButton.value + ". button is click"); } }

and add the buttons like this

<input type="button" value="Button1" onclick="{GetCheckedFruits(this);}" /> <input type="button" value="Button2" onclick="{GetCheckedFruits(this);}" /> <input type="button" value="Button3" onclick="{GetCheckedFruits(this);}" />

If you want to alert the message when the button is clicked, you would have to use an event like this:

<script type="text/javascript">
    function GetCheckedFruits () {
        var elements = document.getElementsByName ("fruit");
        for (var i=0; i < elements.length; i++) {
            elements[i].onclick = function() {
                // You can put anything you want here
                // the variable `this` is the clicked button
                alert ("The " + this.value + " button is click");
            }
        }
    }
</script>

EDIT:

In the case you are working with checkboxes and are trying to get which fruits where selected, this will work:

<script type="text/javascript">
    function GetCheckedFruits () {
        var elements = document.getElementsByName ("fruit");
        for (var i=0; i < elements.length; i++) {
            if (elements[i].checked == 1) {
                alert ("The " + elements[i].value + " button is click");
            }
        }
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM