Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text value in html after append

I create a button with append

var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';
$('.textWord_about> table > tbody').append(row);

I want to change the button text using jquery, by clicking on the button.

This is what am I doing:

$(document).on('click', '.directly-follow', function() {
    event.preventDefault();
    var $post = $(this);
    if ($post.attr("text") == "Follow") {
        $post.text('Unfollow');
        //do something
     }
     else{
        $post.text('Follow');
        //do something
     }

the problem is that the line $post.text('Unfollow') changes the button text but it does not change the defined text in the html tag(text="Follow"). As a result, the functionality does not toggle as I want.(the if is always true!).

How can change the text using jquery?

like image 407
Yeganeh Hajimiri Avatar asked Feb 05 '26 10:02

Yeganeh Hajimiri


2 Answers

To change the value of a custom attribute you have to use attr method.

attr method can be used in order to get the attribute value, but also to set the attribute value.

The method gets the value of an attribute for the first element in the set of matched elements or sets one or more attributes for every matched element.

$(document).on('click', '.directly-follow', function() {
event.preventDefault();
var $post = $(this);
if ($post.attr("text") == "Follow") {
    $post.text('Unfollow');
    $post.attr('text','Unfollow');
 }
 else{
    $post.text('Follow');
    $post.attr('text','Follow');
 }
like image 52
Mihai Alexandru-Ionut Avatar answered Feb 08 '26 00:02

Mihai Alexandru-Ionut


Use attr instead of text. http://api.jquery.com/attr/

var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';

$('.textWord_about> table > tbody').append(row);

$(document).on('click', '.directly-follow', function() {
  event.preventDefault();
  if ($(this).attr("text") == "Follow") {
      $(this).text('Unfollow');
      $(this).attr('text','Unfollow');
   }
   else{
      $(this).text('Follow');
      $(this).attr('text','Follow');
   }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textWord_about">
  <table>
    <tbody>
      
    </tbody>
  </table>
</div>
like image 34
Caique Romero Avatar answered Feb 07 '26 23:02

Caique Romero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!