Adding input fields in Javascript using the onclick button

I have always used javascript or other javascript frameworks to use, but right now I don’t have any frameworks, so I wanted to see if anyone knows how I can do this in direct javascript, if possible.

Basically, I have a div like this

<input type="button" id="more_fields" onclick="add_fields();" value="Add More" /> <div id="room_fileds"> <div class='label'>Room 1:</div> <div class="content"> <span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X </span> <span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small</span> </div> </div> 

What I need when the "Add more" button is clicked, I basically need to add more width and length fields or create an entire structure like the one above with all divs or just insert a new span tag with fields below the existing one.

I know how to do this using jquery or a prototype structure, but unfortunately I cannot use any frameworks for this. Does anyone know how to do this. I would post iv code for this, but I don’t even know where to look.

+6
source share
3 answers

You can use the innerHTML property to add content. Add id="wrapper" to the div surrounding your span elements, and then you can do

 var dummy = '<span>Label: <input type="text"><small>(ft)</small></span>\r\n'; document.getElementById('wrapper').innerHTML += dummy; 

Of course, you do not need id and it can use other DOM methods to access the div , but I find using id easier and cleaner. Quick fiddle here

Also note that you should not embed your css code, do not attach your javascript calls directly inside the DOM elements. Separating DOM, Javascript and CSS makes your life easier.

+11
source

No need to create a new room?

 var room = 1; function add_fields() { room++; var objTo = document.getElementById('room_fileds') var divtest = document.createElement("div"); divtest.innerHTML = '<div class="label">Room ' + room +':</div><div class="content"><span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X</span><span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small></span></div>'; objTo.appendChild(divtest) } 

Demo: http://jsfiddle.net/nj4N4/7/

+6
source

just use innerHTML as follows:

btw I changed the div class="content" to id="content" , you can add a new identifier if you want.

 function add_fields() { var d = document.getElementById("content"); d.innerHTML += "<br /><span>Width: <input type='text'style='width:48px;'value='' /><small>(ft)</small></span> X <span>Length: <input type='text' style='width:48px' value='' /><small>(ft)</small</span>"; } 

DEMO: http://jsbin.com/oxokiq/5/edit

+2
source

All Articles