2
for(i=0;i<formInfo['elementCount'];i++){
    formElement = document.createElement('input');
    formElement.type = 'text';
    formElement.name = formInfo['elementName'][i];

    formElement.setAttribute("value",formInfo['elementValue'][i]); // <-this part

    console.log(formElement);

    newForm.appendChild(formElement);
}

The above code does not work if I use:

formElement.value=formInfo['elementValue'][i];

console.log() returns <input type="text" name="abc"> (value attr is missing)

but it works if

formElement.setAttribute("value",formInfo['elementValue'][i]);

console.log() returns <input type="text" name="abc" value="123">

Why is the formElement.value method not working?

Checked this with both chrome and ff and both have the same results

Jo E.
  • 7,822
  • 14
  • 58
  • 94

2 Answers2

1

Taken from: Properties and Attributes in HTML

The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute.

Community
  • 1
  • 1
sebagomez
  • 9,501
  • 7
  • 51
  • 89
0

The HTML value attribute isn’t necessarily the value that is displayed on the page. It is known as the default value – used when the page is first loaded

You have to set the defaultValue.

Try:

var formElement = document.createElement('input');
formElement.type = 'text';
formElement.defaultValue = "test";
formElement.name="test2";
console.log(formElement);

DEMO

laaposto
  • 11,835
  • 15
  • 54
  • 71