Dynamically modified value of input not reflected in DOM
10,330
Solution 1
The following seems to work for me:
All credit to gnarf here and his formhtml:
jQuery html() in Firefox (uses .innerHTML) ignores DOM changes
So your modified code would be:
<div>
<input value='0'>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>
<script>
(function($) {
var oldHTML = $.fn.html;
$.fn.formhtml = function() {
if (arguments.length) return oldHTML.apply(this,arguments);
$("input,button", this).each(function() {
this.setAttribute('value',this.value);
});
$("textarea", this).each(function() {
// updated - thanks Raja!
this.innerHTML = this.value;
});
$("input:radio,input:checkbox", this).each(function() {
// im not really even sure you need to do this for "checked"
// but what the heck, better safe than sorry
if (this.checked) this.setAttribute('checked', 'checked');
else this.removeAttribute('checked');
});
$("option", this).each(function() {
// also not sure, but, better safe...
if (this.selected) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
});
return oldHTML.apply(this);
};
//optional to override real .html() if you want
// $.fn.html = $.fn.formhtml;
})(jQuery);
setInterval(function() {
$('input').val(parseInt($('input').val()) + 1)
console.log('div.html(): ', $('div').formhtml())
}, 1000)
</script>
Solution 2
Try changing the DOM directly. For example:
<div id="myDiv">
<input id="myInput" value='0'>
</div>
<script>
setInterval(function() {
var v = parseInt(document.getElementById("myInput").value) + 1;
document.getElementById("myInput").setAttribute("value",v);
}, 1000);
</script>
<input type="button" onclick="javascript:alert(document.getElementById('myDiv').innerHTML);" value="Click to see DOM" />
Comments
-
Jesse Aldridge about 2 years
How can I get the DOM to reflect the modified input value?
<div> <input value='0'> </div> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script> <script> setInterval(function() { $('input').val(parseInt($('input').val()) + 1) console.log('div.html(): ', $('div').html()) }, 1000) </script>
-
Jesse Aldridge about 13 years+1 But I would still like to know why the jquery code didn't work.
-
Jesse Aldridge about 13 yearsNope, this doesn't work either. The page runs fine, the problem is that the DOM never changes. Notice that value="0" never changes in the console log.
-
Alejandro García Iglesias over 12 yearsAs the cited question suggests, it's a innerHTML problem. Actually, how different browsers implement innerHTML.
-
MaXon about 5 yearsThis is an old post, and I was searching for the why as well. Here is what I found from another post, which explains the 'why' part. stackoverflow.com/questions/32793811/…