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()
});
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Your my hero! Thanks for the quick response and help.
how to do this while adding a class to each list item?
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>");
});

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.