Home > Net >  How do I get the text of a generated anchor tag nested in a unordered list?
How do I get the text of a generated anchor tag nested in a unordered list?

Time:12-15

I have a script that generates the alphabet and lists them horizontally. What I want to do is click on a letter in the unordered list and and populate it in the textbox.

HTML

<input id="letter" type="text" />
<ul id="test"></ul>

jQuery

$(document).ready(function(){
    for (var i = 65; i <= 90; i  ) {
        $('#test').append('<li><a href="#">'   String.fromCharCode(i)   '</a></li>');
    }
});
var li = $(this).parent();
$(this).click(function(){
var clickedLetter = li.siblings().find('a.active').text();
$("#letter").val(clickedLetter);
});

Here is a codepen. Where am I going wrong?

CodePudding user response:

'this' is referring to window object, it will not give you reference of li.

var li = $(this).parent();

You don't have active class assigned to 'a'

var clickedLetter = li.siblings().find('a.active').text();

Try this code:

$(document).ready(function () {
  for (var i = 65; i <= 90; i  ) {
    $("#test").append(
      '<li><a href="#">'   String.fromCharCode(i)   "</a></li>"
    );
  }
  
   $("#test li").on("click", function (event) {
       var clickedLetter = $(this).find('a').text();
        $("#letter").val(clickedLetter);
   });
});
ul#test li{
  display:inline;
  margin-right:.40em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="letter" type="text" />
<ul id="test"></ul>

CodePudding user response:

You can add one event and use event delegation with jQuery

$(document).ready(function() {
  const ul = $("#test");
  const input = $("#letter");
  for (var i = 65; i <= 90; i  ) {
    ul.append(
      '<li><a href="#">'   String.fromCharCode(i)   "</a></li>"
    );
  }
  
  ul.on("click", "a", function (evt) {
    evt.preventDefault();
    input.val(this.textContent);
    // input.val($(this).text());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="letter" type="text" />
<ul id="test"></ul>

  • Related