Reputation: 1876
this is a part of my html file:
<form id="foo">
<select>
<option value="1" selected>1</option>
<option value="2">2</option>
</select>
</form>
Now when I use the following javascript code, it gives me the exact content of the form:
alert(getElementById("foo").innerHTML);
However, after I change my options withing the form, the above code still returns the previous version of the form's content.
For instance, let's say I've switch my option from "1" to "2". In this case I expect the above javascript code returns the form's content with option "2" selected; but no matter how I change the form, it always return the original version of the form's content.
Upvotes: 7
Views: 1625
Reputation: 156
This works for me:
$('myselect').find('option').prop('selected', false).eq(1).prop('selected', true);
In other words, it sets the 'selected' property the way you want it in all options.
Upvotes: 0
Reputation: 288120
Content attributes show the initial state.
IDL attributes (aka properties) show the current state.
For example, let's say we have a text input like this:
<input value="foo" />
It's default text is "foo". Let's change it to "bar". Then,
input.getAttribute('value')
will be the initial value: "foo"
.input.defaultValue
will be equivalent to the above: "foo"
.input.value
will be the current value: "bar
.var inp = document.querySelector('input');
(inp.oninput = function() {
document.getElementById('attr').textContent = inp.getAttribute('value');
document.getElementById('defVal').textContent = inp.defaultValue;
document.getElementById('val').textContent = inp.value;
})();
<input value="foo" />
<p>Attribute: <span id="attr"></span></p>
<p>Default value: <span id="defVal"></span></p>
<p>Value: <span id="val"></span></p>
In your case it happens something similar. innerHTML
only shows the HTML markup, which includes content attributes (which reflect the initial state) but not IDL attributes (current state).
If you want the current state, read it with IDL attributes instead of using innerHTML
.
Upvotes: 9
Reputation: 10390
This is snippet from the Mozilla Developer Network page for innerHTML
.
More details here: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
This property was initially implemented by web browsers, then specified by the WHATWG and W3C in HTML5. Old implementations may not all implement it exactly the same way. For example, when text is entered into a text input, Internet Explorer changes the value attribute of the input's innerHTML property but Gecko browsers do not.
Upvotes: 3