Jquery not appending values correctly <p>I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code <br></p> <pre><code>&lt;script&gt; function fillin(entire,name,id,key) { if (entire.checked == true) { var split_info = new Array(); split_info = name.split(":"); var div = $("#Inputfields"+id); var till = (div.children("input").length)/4; var current_count = 0; for (var j=0;j&lt;till;j++) { if (document.getElementById("insertname_"+j+"_"+id).value == "" &amp;&amp; document.getElementById("insertnumber_"+j+"_"+id).value == "") { document.getElementById("insertname_"+j+"_"+id).value = split_info[0]; document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1]; break; } else current_count = current_count+1; if (current_count == till) { var x= addnew(id); x =x+1; $("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0]; alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value); document.getElementById("insertname_"+x+"_"+id).text = split_info[0]; //alert(document.getElementById("insertname_"+x+"_"+id).value); //document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1]; } } } else { } } &lt;/script&gt; &lt;script&gt; function addnew(n) { //var id = $(this).attr("id"); var div = $("#Inputfields"+n); var howManyInputs = (div.children("input").length)/4; alert(howManyInputs); var val = $("div").data("addedCount"); var a = '&lt;input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3"&gt;'; var b = '&lt;input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3"&gt;'; var c = '&lt;input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3"&gt;'; var d = '&lt;input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3"&gt;'; var fin = a+b+d+c; $(fin).appendTo(div); div.data("addedCount", div.data("addedCount") + 1); return howManyInputs; } &lt;/script&gt; </code></pre> <p>UPDATED: Thank you all. I was able to find the bug. The culprit was <code>x =x+1;</code>. It should have been <code>x</code></p>