This doesn't apply to form fields.
Let's say I have this in html:
<input id="something" value="myvalue">
<input id="somethingelse" value="myvalue">
And I have javascript that does this:
something.value="ME";
somethingelse.value="TOO";
And I want to manipulate the DOM so that when we inspect the element "something" it reflects this:
<input id="something" value="ME">
If I do this in jquery explicitly it works:
$("#something").attr("value",something.value.toString());
But I need something more generic - I need to change EVERY input item so that it behaves like this.
So I tried:
$("input").each(function () {
$(this).attr("value", this.value.toString());
})
But it doesn't change at all. It leaves it alone.
So I tried this:
$("input").each(function () {
$(this).attr("value", "NeverA");
})
And it doesn't change it either.
But I tried
$("input").each(function () {
alert(this.value.toString());
})
And it is alerting each value - so the selector is good.
What am I doing wrong?
Rick had the proper answer in code - though mine looks correct in the question, the code I had in my jsfiddle must have had some sort of unreported error because it just didn't work. Pasting in the code from Rick's fiddle worked fine. Here's my fiddle with the answer and a few more types of input fields.
The answer:
<input id="something" value="myvalue">
<input id="somethingelse" value="SE">
<input id="ANum" type="number" value=99>
<input id="button" type="button" value="OK">
<script>
something.value = "NEVER";
button.value = "Not OK";
ANum.value = 9342;
$("input").each(function () {
$(this).attr("value", this.value);
})
</script>
Fiddle for this:
http://jsfiddle.net/t2nrkeyt/