Dynamically changed input value not reflected in the DOM

How can I make the DOM reflect the changed 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> 
+7
source share
3 answers

It seems to me that the following works:

http://jsfiddle.net/h8AP8/1/

All credits for gnarf are here and its formhtml:

jQuery html () in Firefox (uses .innerHTML) ignores DOM changes

Thus, your modified code will look like this:

 <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> 
+4
source

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" /> 
+5
source

Sorry, but the problem is not with the sample code you provided. Or, when it's the only html on your page, you miss the start and end tags.

This clean page works fine on my machine:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head></head> <body> <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> </body> </html> 

Or are you testing in Internet Explorer? In this case, delete the line that is written to the error console:

 console.log('div.html(): ', $('div').html()) 
0
source

All Articles