javascript - JQuery: adding items to list and keeping count of items -


i have list of items(for have included one), , trying add more items list. while can insert new item @ end of list, can not id number set, comes out 0.

<script>     var count = $("#playlist").children().length;      $(document).ready(function(){       $("button").click(function(){         $("ul").append(           $('<li>').attr('id', 'list['+ count +']').append(             $('<div>').attr('class','item').append(               $('<fieldset>').append(                 "<input id='list[i][name]' name='list[i][name]' type='text' class='auto' size='40' value ='new "+ count +"'>"               )             )           )         )       })     }); </script>   </head> <body> <div class='holder'>    <ul id="playlist">         <li id='list[1]' ><div class='item'><fieldset>             <input id='list[1][name]' name='list[1][name]' type='text' class='auto' size='40' value ='one' />         </fieldset></div></li>    </ul>    <br> <button>add new list item</button> </div> 

put count variable inside event listener, increases when clicking

$(document).ready(function() {     $("button").click(function() {         var count = $("#playlist").children().length;         $("ul").append(             $('<li>').attr('id', 'list[' + count + ']').append(                 $('<div>').attr('class', 'item').append(                     $('<fieldset>').append(                         "<input id='list[i][name]' name='list[i][name]' type='text' class='auto' size='40' value ='new " + count + "'>"                     )                 )             )         )     }) }); 

right you're getting count before document loads, when #playlist isn't accessible, count 0.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -