Mayuresh Patil
Mayuresh Patil

Reputation: 2200

How to change text of buttons after clicking on them for multiple buttons?

I am using multiple buttons and my problem is when i am clicking on any button then the text changes of first button, but not that button on which i am clicking. I am using here same button id for all buttons but it is hard to use different button id's for such multiple buttons so what is any other simple way without using different id's. I want to change only one button at a time on which i am clicking but not other buttons. PLEASE HELP..!

html code

user1
<input type="button" value="Connect" id="toggle" onclick="myFunction()">
user2
<input type="button" value="Connect" id="toggle" onclick="myFunction()">
user3
<input type="button" value="Connect" id="toggle" onclick="myFunction()">

and so on...

and js function is

function myFunction()
    {
        var change = document.getElementById("toggle");
        if (change.value=="Connected") change.value = "Connect";
        else change.value = "Connected";
    }

Upvotes: 0

Views: 1966

Answers (2)

sjramsay
sjramsay

Reputation: 555

You can do it like this as well? You can change your onclick events as follows:

Change onlick functions to this: onclick ="myFunction(this)"

And Update your javascript function to be like the following:

function myFunction(obj) {
    if (obj.value == "Connected")
        obj.value = "Connect";
    else
        obj.value = "Connected";
}

Upvotes: 2

Sagar Jajoriya
Sagar Jajoriya

Reputation: 21

You cant use same Id for multiple elements. Simply you can use class instead of Id. Then your code will look like that :

$(".toggle").click(function(){}
    $(this).text("Whatever");
})

Upvotes: 1

Related Questions