Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - change button's text on click works only on second click

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.

like image 704
jimmypage Avatar asked Aug 12 '15 08:08

jimmypage


2 Answers

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

like image 123
DGS Avatar answered Oct 08 '22 19:10

DGS


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

like image 34
Sougata Bose Avatar answered Oct 08 '22 18:10

Sougata Bose