Skip to content Skip to sidebar Skip to footer

Reading Innerhtml Of Html Form With Value Attribute (& Its Value) Of Input Tags

I have a html form with some input fields. Instead of reading and sending the values of input fields by document.ipForm.userName.value , I need to send the whole html content to h

Solution 1:

That's because value is a property when the textbox is filled in, not an attribute. This means that .value works fine, but it's not part of the actual DOM as an attribute (like <input value="...">).

You'd need to set it explicitly:

document.getElementById("html").onclick = function() {
  var elems = document.getElementsByName("ipForm")[0]
    .getElementsByTagName("input");

  for (var i = 0; i < elems.length; i++) {
    // set attribute to property value
    elems[i].setAttribute("value", elems[i].value);
  }

  alert(document.getElementsByName("ipForm")[0].innerHTML);
};
<formname="ipForm">
  UserName : <inputtype="text"name="userName"></form><buttonid="html">get innerHTML</button>

View on jsFiddle

Solution 2:

You can also write an input which will change itself his attribute, like this :

(...)

UserName : <inputtype="text" name="userName" onChange="this.setAttribute('value', this.value);"> 

And for checkboxes :

onClick="if (this.checked) { this.setAttribute('checked', null); } else { this.removeAttribute('checked'); }"

Enjoy :)

Post a Comment for "Reading Innerhtml Of Html Form With Value Attribute (& Its Value) Of Input Tags"