2

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?

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

What is the use of this.rel?
Cheap way to use small-scale element storage until Internet Explore 7 is gone forever. By putting the counter in the rel property of the button, a global variable is avoided.
Should you use a default value if this.rel is undefined? this.rel || 0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.