Reputation: 2200
I am using multiple buttons which are created by button tag, I want to change text of each button separately when i am clicking on that button only.
I am trying to do with following code but it is not working at all..
how can i do it by using button tag...
Thanks...
Html code is
user1
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user2
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user3
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
and js code is
<script>
function myFunction(obj) {
if (obj.value == "Connected")
obj.value = "Connect";
else
obj.value = "Connected";
}
</script>
Upvotes: 1
Views: 75
Reputation: 177960
You need to change innerText instead of value and it is case sensitive
Buttons have value attributes but not href attributes
NOTE if the buttons are in a form, you need to use type="button"
or add preventDefault to not submit the form
Inline plain JS:
function myFunction(obj) {
obj.innerText = obj.innerText == "Connect" ? "Connected" : "Connect";
}
user1
<button class="toggle" onclick="myFunction(this)">Connect</button> user2
<button class="toggle" onclick="myFunction(this)">Connect</button> user3
<button class="toggle" onclick="myFunction(this)">Connect</button>
jQuery - with a link
$(function() {
$(".toggle").on("click", function() {
var text = $(this).text(), link = $(this).data("url");
$(this).text(text == "Connect" ? "Connected" : "Connect");
$("#somediv").load(url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
user1
<button data-url="user1.html" class="toggle">Connect</button> user2
<button data-url="user2.html" class="toggle">Connect</button> user3
<button data-url="user3.html" class="toggle">Connect</button>
Upvotes: 5
Reputation: 138
try this you shoud use obj.innerText instead of obj.innerTex
<script type="text/javascript">
function myFunction(obj) {
if (obj.innerText == "Connected")
obj.innerText = "Connect";
else
obj.innerText = "Connected";
}
</script>
Upvotes: 1
Reputation: 21617
As you added the jquery
tag, you could do this:
function myFunction(obj) {
var o = $(obj);
if (o.text() === "Connected")
o.text("Connect");
else
o.text("Connected");
}
Fiddle: https://jsfiddle.net/j0z495et/
Upvotes: 1
Reputation: 30739
You need to use firstChild.nodeValue
instead of value
function myFunction(obj) {
if (obj.firstChild.nodeValue == "Connected")
obj.firstChild.nodeValue = "Connect";
else
obj.firstChild.nodeValue = "Connected";
}
user1
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user2
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user3
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
Upvotes: 1