Shristi Sharma Shristi Sharma - 4 months ago 16
Javascript Question

Append li to parent ul

I'm trying to get text from an input to add to an existing ul in the parent using jquery, but when I do this:

$("input[type = 'text']").keypress(function(event){
if(event.which === 13){
//grabbing new todo from input
var todoText = $(this).val();
$(this).val("");
//create a new li and add to ul
$(this).parent().append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
}
});


it adds a new li directly to the parent. I realized I forgot to mention that I wanted it to be added to the existing ul, so I tried changing this:

//create a new li and add to ul
$(this).parent("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");


but it still didn't work, and now it doesn't even add anything anywhere. Maybe it's because I have the wrong syntax or something?

Here is an example of how my jade is structured:

.frame
.bit-2
h1
| text
i.fa.fa-plus
input(type='text', placeholder='text')
ul
li
span
i.fa.fa-trash
| text
li
span
i.fa.fa-trash
| text


Any idea of what's going on?

Answer

Please use .next() function like below.

$(document).ready(function(){
  $("input[type = 'text']").keypress(function(event){

    if(event.which === 13){
      //grabbing new todo from input
      var todoText = $(this).val();
      $(this).val("");
      //create a new li and add to ul
      $(this).next("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
    }
  });
});

For demo please check below snippet.

$(document).ready(function(){
  $("input[type = 'text']").keypress(function(event){
    
    if(event.which === 13){
      //grabbing new todo from input
      var todoText = $(this).val();
      $(this).val("");
      //create a new li and add to ul
      $(this).next("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>
<ul><li>First</li></ul>