8

Well I have this code in view:

<input id="CI.SiteName" type="text" value="" name="@@CI.SiteName" disabled="">

and then I doing some event that would call this function:

chooseSite = function () {
    var url = "/main/Ajax/GetSiteDetail?" +
        "&cid=" + escape(idSite);

    var ajx = sendAJAX(url, true);

    ajx.onreadystatechange = function () {
        if (ajx.readyState == 4) {
            var result = ajx.responseText;      
            result = "TOP";
            document.getElementById("CI.SiteName").value = result;
        }   
    }
}

in browser it changed to "TOP" but when I inspect element with firebug, the VALUE attribute of INPUT still "", not changed.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Mr.Rendezvous
  • 1,933
  • 5
  • 20
  • 34
  • 1
    Why did you ask for the getElementById() method? It was never supposed to change anything. – Bergi Apr 27 '12 at 07:35

2 Answers2

24

The value attribute is not synced with the actual value; that's what the value property is for.

This is not a problem though since you'll never use .getAttribute('value') but use the property .value to access the current value.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <meta charset="UTF-8" />
</head>

<body>
  <div id="app"></div>
  <div id="buttons">
    <button id="1" data-text="one">1</button>
    <button id="2" data-text="two">2</button>
    <button id="3" data-text="three">3</button>
    <button id="4" data-text="four">4</button>
    <button id="5" data-text="five">5</button>
    <input id="inp" value=""></input>
  </div>

  <script>
    const onClick = function() {

      var dataTextBtnField = this.getAttribute("data-text");
      var currentData = document.getElementById("inp").value

      var showValue = currentData + dataTextBtnField
      document.getElementById("inp").setAttribute("value", showValue);
      document.getElementById("inp").value = showValue;
    }

    const onChange = function() {
      this.setAttribute("value", this.value);
    }

    document.getElementById('1').onclick = onClick;
    document.getElementById('2').onclick = onClick;
    document.getElementById('3').onclick = onClick;
    document.getElementById('4').onclick = onClick;
    document.getElementById('5').onclick = onClick;
    document.getElementById('inp').onchange = onChange;
  </script>

</body>

</html>
document.getElementById("inp").setAttribute("value", showValue);

Using this will change in the HTML code only, and won't reflect in the view.

document.getElementById("inp").value = showValue;

Using this will change in the view only, and not in the code.

Use both lines to change at both the locations.

Comment the above-mentioned lines in the attached snippet to observe the same.