Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a ul li with appended text from input with Jquery

I have a form that has a text input with an add button. When you click the add button it gets the text from the input and places it below in another div. I need it to be in a dynamically created unordered list that also places the text from the input inside. I need the output to look like

<ul> <li>text from input</li> <li>text from input again</li> </ul>

Im not sure how to properly place the append to create the list and append the text inside. I can get the text value easily and output it just not into a list. Any help about appending would be great.

like image 488
user2066695 Avatar asked Dec 07 '22 09:12

user2066695


1 Answers

HTML:

<input type="test" id="inputName" />
<button id="btnName">Click me!</button>

<ul class="justList"></ul>

JS:

$('#btnName').click(function(){
    var text = $('#inputName').val();
    if(text.length){
        $('<li />', {html: text}).appendTo('ul.justList')
    }
});

Here is the demo :

http://jsfiddle.net/J5nCS/

UPDATE:

for your comments :

here is the url :

http://jsfiddle.net/J5nCS/1/

$('#btnName').click(function(){
    var text = $('#inputName').val() + '<button>x</button>';
    if(text.length){
        $('<li />', {html: text}).appendTo('ul.justList')
    }
});

$('ul').on('click','button' , function(el){
    $(this).parent().remove()
});
like image 177
AlexC Avatar answered Dec 28 '22 08:12

AlexC