最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Appending a new textbox onclick of button - Stack Overflow

programmeradmin1浏览0评论

Am trying to write a simplest code, like onclick of button a new textbox with unique id should be assigned and appended to the existing ones.

function appendRow()
{
var x = 1;
for(var i=0; i < x; i++)
{
    var d = document.getElementById('div');
    d.innerHTML = "<input type='text' id='tst"+ x +"'><br >";
}
++x;
}

HTML:

<div id="div">
 <button onclick ="appendRow()" value="Add Row">Add Row</button>
 </div>

This might be very simple for techies.

Thanks.

Am trying to write a simplest code, like onclick of button a new textbox with unique id should be assigned and appended to the existing ones.

function appendRow()
{
var x = 1;
for(var i=0; i < x; i++)
{
    var d = document.getElementById('div');
    d.innerHTML = "<input type='text' id='tst"+ x +"'><br >";
}
++x;
}

HTML:

<div id="div">
 <button onclick ="appendRow()" value="Add Row">Add Row</button>
 </div>

This might be very simple for techies.

Thanks.

Share Improve this question asked Sep 18, 2014 at 10:52 BaskyBasky 1011 gold badge3 silver badges8 bronze badges 1
  • Aside from your code replacing the button instead of appending, what doesn't work in the code? – Ynhockey Commented Sep 18, 2014 at 10:54
Add a ment  | 

1 Answer 1

Reset to default 4

You are replacing the button. You have to append the new div to the already created elements. Try to use += instead of =.

Also there is not need for a loop. You can assign unique id with just an inceasing var

Try:

var x=1
function appendRow()
{
   var d = document.getElementById('div');
   d.innerHTML += "<input type='text' id='tst"+ x++ +"'><br >";
}

DEMO

发布评论

评论列表(0)

  1. 暂无评论