Patrick Patrick - 4 months ago 7
jQuery Question

Change text of a link to this element's text

I am trying to update the text of a link with the text from the item clicked. I thought that $(this).text(); would capture the element's text as a jQuery object, but nothing is happening. I tried writing a fiddle but it gives me a post error.

Fiddle: https://jsfiddle.net/pitrik/hjd5fq18/

$(".country-label").on("click", function() {
var updateCountry = $(this).text();
console.log(updateCountry);
$('#country-label').text(updateCountry);
localStorage.setItem('CountryName', updateCountry);
});

<a href="#" id="country-label">Canada</a>
<ul class="dropdown">
<li><label>Select your Country</label></li>
<li><a href="#" class="country-label">United States</a></li>
<li><a href="#" class="country-label">Australia</a></li>
<li><a href="#" class="country-label">France</a></li>
<li><a href="#" class="country-label">Germany</a></li>
</ul>

Answer

The issue(in your Fiddle) is that you're passing a string, updateCountry, instead of the variable. The jQuery should look like this:

$(".country-label").on("click", function(event) {
  event.preventDefault();
  var updateCountry = $(this).text();
    $('#country-label').text(updateCountry);
    console.log(updateCountry);
});

You also did not include jQuery in your Fiddle, I have updated it here:

Updated Fiddle

Comments