I am a php programmer .I have a user input form in which a person should be able to add as many text boxes (to enter muliple email ids ) as he wishes , by the click of a button.
You can create elements via document.createElement, and append them to a form via appendChild, like so:
var textbox = document.createElement('input');
textbox.type = 'text';
document.getElementById('theForm').appendChild(textbox);
(That assumes the form has an id
= "theForm", but you can get the reference to the form other ways.)
If you want to wrap it in a label, that's easy, too:
var label, textbox;
label = document.createElement('label');
label.appendChild(document.createTextNode('Another email address: '));
textbox = document.createElement('input');
textbox.type = 'text';
label.appendChild(textbox);
document.getElementById('theForm').appendChild(label);
Live example
If you kick around the DOM specs (DOM Core 2 is the most widely-supported at present, as is the HTML stuff on top of it; DOM Core 3 is getting some support now), you'll find other things you can do — like inserting into the form in the middle rather than appending to the end, etc.
Most of the time, you can use innerHTML
to add to DOM structures (it's supported by every major browser, and is getting standardized as part of HTML5), but there are some browser quirks around form fields, specifically, which is why I've gone with the DOM interface above.
You haven't said you're using a library, and so the above is pure JavaScript+DOM. It's fairly simple, but in real world use you can quickly run into complications. That's where a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others can save you time, smoothing over browser differences and complications for you, allowing you to focus on what you're actually trying to do.
For instance, in the linked example, I had to provide a hookEvent
function to handle the fact that some browsers use the (standardized) addEventListener
function, while IE prior to IE9 uses attachEvent
instead. And libraries will handle the form field quirks I was talking about, allowing you to specify your fields using straight HTML, like this:
Using jQuery:
$("#theForm").append("<label>Another email address: <input type='text'>");
Live example
Using Prototype:
$("theForm").insert("<br><label>Another email address: <input type='text'>");
Live example