BRG BRG - 5 months ago 7
jQuery Question

Get the text of <a> in <li> when a button clicks

Hello I am building a feedback form with a custom rating list which looks like this:

<ul class="star-rating" id="rating">
<li><a href="#" class="one-star">1</a></li>
<li><a href="#" class="two-stars" >2</a></li>
<li><a href="#" class="three-stars">3</a></li>
<li><a href="#" class="four-stars">4</a></li>
<li><a href="#" class="five-stars">5</a></li>
</ul>

<a href="#" class="buttonNext btn btn-success">Next</a>


When the user selects clicks the rating i have the next button in which i do this:

<script>
$(document).ready(function() {
$('.buttonNext').addClass('btn btn-success').click(function() {
var text = $("#rating li a").text();
alert("Text: " + text);
});
});
</script>


But in the alert i get Text: 12345.

What am i doing wrong and not getting the correct text?

How will i be able to get only 3 if user clicked 3 and so on?

Any help will be appreciated!!!

Answer

Try

 $(document).ready(function() {

    $('ul#rating li a').click(function() {
      $('ul li a').removeClass("active");
      $(this).addClass("active");
    });

    $('.buttonNext').addClass('btn btn-success').click(function() {
      var text = $("#rating li a.active").text();
      alert("Text: " + text);
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="star-rating" id="rating">
  <li><a href="#" class="one-star">1</a></li>
  <li><a href="#" class="two-stars">2</a></li>
  <li><a href="#" class="three-stars">3</a></li>
  <li><a href="#" class="four-stars">4</a></li>
  <li><a href="#" class="five-stars">5</a></li>
</ul>
<button class="buttonNext">
  Submit
</button>

Demo : JsFiddle