code_strider
code_strider

Reputation: 17

Adding a new 'li' each time a user enters in text and hits the button

$(document).ready(function() {
$('#btn1').click(function() {
 $('li').after($( "#txt1" ).val());
});
});

This works to add the text after the first li but when I enter in new text, it places it inside the same li - The question is: How do I get the jquery code to work to enter in a new li each time?

Upvotes: 0

Views: 90

Answers (2)

Hemal
Hemal

Reputation: 3760

I think the following updated code with fiddle should work much more smooth.

You should use a parent element for li, so that you can use .append() function

WORKING FIDDLE

HTML

<ul>
    <li>ok</li>
    <li>ok</li>
    <li>ok</li>
    <li>ok</li>
</ul>
<input id="txt1" /><input type="submit" id="btn1">

JQUERY CODE

$(document).ready(function() {
    $('#btn1').click(function() {
        //$('li').last().after('<li>' + $( "#txt1" ).val() + '</li>');
        $("ul").append("<li>"+$("#txt1").val()+"</li>");
        $("#txt1").val("").focus();//This will clear previous text and set focus
    });
});

Upvotes: 0

skbly7
skbly7

Reputation: 1162

Here is what you are willing to do :

http://jsfiddle.net/sykkadfk/5/

You need to append <li> & </li> as told by @Tushar, but also, select only the last() element of li, please check the link above for demo.

$(document).ready(function() {
    $('#btn1').click(function() {
        $('li').last().after('<li>' + $( "#txt1" ).val() + '</li>');
    });
});

Upvotes: 1

Related Questions