views:

11

answers:

2

I have a complex form that has a static section and one that can have from 0 to many divs that containing radio buttons, textfields and textareas.

I'm wondering what's the best way to add elements to the section that has a variable amount of form inputs. I have a working solution, but it's probably not the best: I use javascript to add a chunk of html code and append it to the div containing the variable amount of input fields. In the code sample below, my javascript code would do something like

Javascript

document.getElementId('dynamic_form_stuff').innerHTML += "<div id='element3'>Form stuff</div>";

HTML

<form>
  <div id="static_form_stuff">
    form fields
  </div>

  <div id="dynamic_form_stuff">
    <div id="element1">
      Radio buttons stuff
      Text field stuff
      Text area stuff
    </div>      
    <div id="element2">
      Radio buttons stuff
      Text field stuff
      Text area stuff
    </div>
  </div>
</form>
A: 

I would personally do something like:

var elem = document.getElementId('dynamic_form_stuff');
var div = document.createElement('div'); // create element
div.setAttribute('class', 'myclass');  // define attributes
elem.appendChild(div);
// and/or more code.....

This gives me more control in adding attributes and style there.

Sarfraz
Style should be done by css, and it is easy to add that while using innerHTML, but more control is a good thing, as long as you don't mind it taking longer to render.
James Black
A: 

I think this largely depends on what you are doing elsewhere, and how many items you are adding, as well as how you want to add event handlers.

I tend to find it easier to use the DOM methods if I need to add event handlers, but if you are just adding to a form with a submit button, then using innerHTML is faster, as shown here: http://www.quirksmode.org/dom/innerhtml.html.

James Black
Thanks for the answer!So I guess I'm in one of those situations of "if it ain't broke, don't fix it" ? It just didn't look right and kinda hard to maintain.The solution shown by sAc (below) was cleaner in a way but just as confusing as I have many elements (tables, inputs, images, etc.) that would go in the div "elements3". I'd have a bunch of elements to create and append.
FrancoisCN
It depends if you are adding event handlers, or how fast you want it to render. There are trade-offs here.
James Black