Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(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?

>Solution :

‘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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading