john
john

Reputation: 1330

onclick create textbox

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?

Upvotes: 2

Views: 10026

Answers (1)

Chris Baker
Chris Baker

Reputation: 50592

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 & company
      add_btn.addEventListener('click', handler_func, false);

Fiddle: http://jsfiddle.net/rkYpD/1/

Upvotes: 6

Related Questions