How to dynamically create ul li with added text from input using JQuery
I have a form that has text input with an add button. When you click on 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 generated unordered list that also puts text from the input inside. I need an output to make it look like
<ul>
<li>text from input</li>
<li>text from input again</li>
</ul>
I'm not sure how to properly position my list creation app and add text inside. I can easily get the text value and output it just not to the list. Any help on adding would be great.
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's a 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()
});
something like that?
$("#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>");
});
You are looking for jQuery appendTo()
$("button").click(function(){
$("<li>"+$("input").val()+"</li>").appendTo("ul");
});
demo: http://jsfiddle.net/u74Ag/
This might be helpful
- http://api.jquery.com/appendTo/
- http://api.jquery.com/append/