SMHasnain
SMHasnain

Reputation: 706

jquery .text() not working on click

I am trying to make a togable anchor tag, till now achieved this I want it to toggle both fa icon and the text on click. so far fa icon toggles but cant toggle the text can anyone show me how to do it.

html

<h5 class="text-muted"> Education <a id="btnExp" class="fa fa-plus">ADD</a> </h5>

JS

$('h5 #btnExp').on('click', function () {
    $("h5 #btnExp").toggleClass("fa fa-minus fa fa-plus");
    $("#btnExp").text("123");
});

Upvotes: 1

Views: 402

Answers (2)

Satpal
Satpal

Reputation: 133403

You need to prevent its default action as element is anchor. Also wrap your code in document-ready handler.

$(document).ready(function() {
  $('h5 #btnExp').on('click', function() {
    $("h5 #btnExp").toggleClass("fa fa-minus fa fa-plus");
    $(this).text($(this).text() === '123' ? 'ADD' : '123'); //Also toggle text
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5 class="text-muted"> Education <a id="btnExp" class="fa fa-plus">ADD</a> </h5>

Upvotes: 3

Arijit Mukherjee
Arijit Mukherjee

Reputation: 3875

Change $("#btnExp").text("123"); to $(this).text("123");

Upvotes: 3

Related Questions