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

javascript - onclick create textbox - Stack Overflow

programmeradmin2浏览0评论

this is a dumb question but for some reason i can't figure it out or find a simple example anywhere. all i want is a button that when clicked, creates a textbox with the same name +1.

<input type="button" value="Show" onclick="blah" />
<!-- Button Gets Clicked -->
<input type="text" name="added1" /> 
<!-- Button Gets Clicked -->
<input type="text" name="added2" />
<!-- Button Gets Clicked -->
<input type="text" name="added3" />

maybe javascript!? any ideas?

this is a dumb question but for some reason i can't figure it out or find a simple example anywhere. all i want is a button that when clicked, creates a textbox with the same name +1.

<input type="button" value="Show" onclick="blah" />
<!-- Button Gets Clicked -->
<input type="text" name="added1" /> 
<!-- Button Gets Clicked -->
<input type="text" name="added2" />
<!-- Button Gets Clicked -->
<input type="text" name="added3" />

maybe javascript!? any ideas?

Share Improve this question asked Jun 14, 2011 at 18:17 johnjohn 1,3304 gold badges21 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Inline javascript is not the best way to approach this, but...

<input type="button" value="Show" onclick="var e = document.createElement('input'); e.type='text'; e.name = 'added'+this.rel; this.rel = parseFloat(this.rel)+1; this.parentNode.appendChild(e); return false;" />

Better to separate your presentation from your script:

HTML:

<input type="button" value="Show" id="add_btn" />

Cross-browser Javascript:

var handler_func = function () {
    var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
    var e = document.createElement('input');
    e.type='text';
    e.name = 'added'+i;
    this.rel = i+1;
    this.parentNode.appendChild(e);
    return false;       
}

var add_btn = document.getElementById('add_btn');
if(add_btn.attachEvent)
      add_btn.attachEvent('onClick', handler_func);
else if(add_btn.addEventListener) //Firefox & pany
      add_btn.addEventListener('click', handler_func, false);

Fiddle: http://jsfiddle/rkYpD/1/

发布评论

评论列表(0)

  1. 暂无评论