I’ve read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails">Fill Details</a>
So, a user will enter an integer value (I’m checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I’m not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an
onclickevent handler in order to get the input value for the text field. Make sure you give the field an uniqueidattribute so you can refer to it safely throughdocument.getElementById():If you want to dynamically add elements, you should have a container where to place them. For instance, a
<div id="container">. Create new elements by means ofdocument.createElement(), and useappendChild()to append each of them to the container. You might be interested in outputting a meaningfulnameattribute (e.g.name="member"+ifor each of the dynamically generated<input>s if they are to be submitted in a form.Notice you could also create
<br/>elements withdocument.createElement('br'). If you want to just output some text, you can usedocument.createTextNode()instead.Also, if you want to clear the container every time it is about to be populated, you could use
hasChildNodes()andremoveChild()together.See a working sample in this JSFiddle.