I have many buttons that have same class but different id on each. The following html button is added beside each $data element.
<button name="toHomepageButton" id = "<?php echo $data->id ?>" class="frontpage"><?php if ($data->isChecked == 1) echo "Remove from homepage"; else echo "Promote to homepage" ; ?> </button>
Now I want to change individual button's text based on if it is clicked. i.e. if a button is clicked and it has text "Promote to homepage", it's text should change to "Remove from homepage" and vice versa. I used the following jquery code to do so.
$('.frontpage').on('click', function() {
var id = this.id;
$("#"+id).html($("#"+id).html() == "Promote to homepage" ? "Remove from homepage" : "Promote to homepage");
});
Now this code works but only on second click. i.e. when I click a promote to homepage button, it's text won't change but if I click it again, the text changes. What am I doing wrong? Please help.
Looks like you might be adding in extra spacing when you echo out from PHP
Try
<button name="toHomepageButton" id = "<?php echo $data->id ?>" class="frontpage"><?php if ($data->isChecked == 1) echo "Remove from homepage"; else echo "Promote to homepage" ; ?></button>
Notice the removed space after the echo. This means that $("#"+id).html() == "Promote to homepage"
Will never never true however $("#"+id).html() == "Promote to homepage "
Would be
In this case you should use text()
instead of html()
as it has simple text.
Take care of the spaces. Use $.trim
before comparing the values.
Try with -
$('.frontpage').on('click', function() {
var $this = $(this);
var text = ($.trim($this.text()) == "Promote to homepage") ? "Remove from homepage" : "Promote to homepage";
$this.text(text);
});
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With