Ramez GaIal Ramez GaIal - 3 years ago 175
jQuery Question

how to append new <li> in jquery

I finished lesson 'append' in jquery and wanted to make simple list
that displays input value and creates new other list to do the same after submitting, but it overwrites the previous one,
this is all i could do, may you tell me what i have missed ?
thanks and i am sorry i am beginner



$(function () {
$('#submit').on('click', function() {

var myTitle = $('#title').val();
var myParagraph = $('#par').val();
$('.list li').html('<h1>' + myTitle +'</h1></br><p>' +myParagraph+'</p>');

if ( $('.list .item').length > 1){
$(".list").append('<li></li>');

}

});



});

ul {
list-style: none;
margin: 0;
padding: 0;
}
li{
border-left: 3px solid orangered
}
input{
display: block
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='list'>
<li class='item'>
<h1 class='title'></h1>
<p class='paragraph'></p>
</li>
<ul>
<label>title</label>
<input id='title' type='text' required>
<label>Paragraph</label>
<input id='par' type='text' required>
<input id='submit' type='submit' >




Answer Source
$('.list li').html(something);  //will overwrite
$('.list li').append(something); //will append to end
$('.list li').prepend(something); //will append to beginning

why am I using counter variable?

Because you have initially one li, so length returns 1 even though data not appended. And after appending data lenth will be still 1 only.

$(function() {
    var counter = 0;
    $('#submit').on('click', function() {
        counter++;
        var myTitle = $('#title').val();
        var myParagraph = $('#par').val();

        if (counter > 1) {
            $('.list').prepend('<li><h1>' + myTitle + '</h1></br><p>' + myParagraph + '</p></li>');
        } else {
            $('.list li').html('<h1>' + myTitle + '</h1></br><p>' + myParagraph + '</p>');
        }

    });
});
ul {
   list-style: none;
   margin: 0;
   padding: 0;
}
li{
   border-left: 3px solid orangered
}
input{
   display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='list'>
  <li class='item'>
     <h1 class='title'></h1>
     <p class='paragraph'></p>
  </li>
<ul>
<label>title</label>
<input id='title' type='text' required>
<label>Paragraph</label>
<input id='par' type='text' required>
<input id='submit' type='submit' >

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download