4

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.

0

3 Answers 3

15

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()
});
3
  • I also need to create a little X button to delete a list item in case someone typed the wrong one. Basically like how stackoverflow allows you to delete tags from your question. Would save me some time if someone could post some sample code. Commented Feb 19, 2013 at 1:12
  • Your my hero! Thanks for the quick response and help. Commented Feb 19, 2013 at 17:47
  • 1
    how to do this while adding a class to each list item? Commented Oct 2, 2016 at 20:14
0

something like this?

$("#yourbutton").click(function() {
    //uncomment this if you want to wipe the list before adding the LI node:
    //$("#yourUL").empty();

    $("#yourUL").append("<li>" + $("#yourinputtextbox").val() + "</li>");
});
0

You are looking for jQuery appendTo()

$("button").click(function(){
    $("<li>"+$("input").val()+"</li>").appendTo("ul");
});

demo: http://jsfiddle.net/u74Ag/


This might be useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.