Manatax
Manatax

Reputation: 4223

how to set form attribute on a createElement input with Javascript

can someone please help me out? I'm trying to create an input dynamically with this function, but the "form" attribute is not being set.

function addInput(parentID,inputNAME) {
    var padre = document.getElementById(parentID);
    var container = document.createElement("input");
    container.type = "text";
    container.name = inputNAME;
    container.value = "";
    container.form = 'extra';
    var enter = document.createElement("br");
    padre.appendChild(container);
    padre.appendChild(enter);
}

I've also tried with this:

container.formName = 'extra';
container['form'] = 'extra';
container.attributes['form'] = 'extra';
container.createAttribute('form','extra')

EDIT:
Answer:
container.setAttribute("Form",'extra');

Upvotes: 3

Views: 10637

Answers (2)

Manatax
Manatax

Reputation: 4223

I've used

container.setAttribute("Form",'extra');

and it appears to be working in FF, Chrome and Opera.

Upvotes: 9

RobG
RobG

Reputation: 147413

Dunno why "am not i am" delete his/her answer, it is mostly correct. The form property is specified in the DOM 2 HTML spec as readonly and references the form that a form control is in. If it isn't in a form, it will be undefined.

The form attribute is new in HTML5 and is intended to associate a control with a form other than the one it is in. This is intended to be used for nested forms.

Setting a form attribute on an input element may have unpredictable results. In browsers conforming to HTML5, if the value of the form attribute is the ID of another form in the document, the control will be associated with that form so its form property is a reference to the form and its form attribute will be a string (the ID of the associated form). Otherwise, the attribute value will not be reflected in the control's form DOM property but may keep the attribute value as set.

IE has always messed up attributes and properties, IE 6 replaces the form property with the attribute value regardless. Maybe later versions behave differently, perhaps one of them supports HTML5.

The following may help:

<form id="form0">
  <div>
    <input type="button" form="form1" onclick=
      "alert('form property is: ' + this.form + ' ' + this.form.id + 
             '\nform attribute: ' + (typeof this.getAttribute('form')) +
             ' ' + this.getAttribute('form'))
      " value="Show form property  and attribute">
  </div>
</form>
<form id="form1"><div></div></form>

Upvotes: 2

Related Questions