i have many follow buttons and each button is linked with a specific user. now when a user clicks on the button it should change from follow to following for each button that is clicked in the div
i tried achieveing this by using this method:
$(document).ready(function(){
$('.msg-action').each(function(){
$("#follow-button2").click(function(){
if ($("#follow-button2").text().trim() == "Follow"){
$("#follow-button2").text('Following');
}else{
$("#follow-button2").text('Follow');
}
});
});
});
but it doesn’t seem to work.
if i do this:
$(document).ready(function(){
$("#follow-button2").click(function(){
if ($("#follow-button2").text().trim() == "Follow"){
$("#follow-button2").text('Following');
}else{
$("#follow-button2").text('Follow');
}
});
});
only the first instance of a button will be changed and others wont, because jquery understands the first instance of the class or id i am referring to.
my HTML CODE:
while($row3 = $query->fetch())
{
?>
<div Class="inside-card"
<td>
<div class="msg-body">
</a>
</img>
<div class="msg-action">
<form method="POST" action='' name="followForm">
<button id="follow-button2" class='msg-icon' name="follow" type="submit" value="follow" onclick=""><span id="follow_id">Follow</span>
<input type="hidden" value="<?php echo $follower_username; ?>" name="follow_id"/>
</button>
?>
so is there a way to use jquery to change every clicked button?
3
Answers
First get all follow buttons and create an array to make it easier to iterate over the collection.
Then attach the event to each follow button to change text when someone clicks on it.
In your loop, you’re iterating parent elements but actually calling the single child element with this:
If you want to access every element with
id="follow-button2"
, you have to iterate child selector and access it with$(this)
inside. Try something like this:Add this
span
inside your each buttonChange the
id
of your button toclass
likeand Add this
js
Here is the jsfiddle, tested, working 100% correct.