Reputation: 2910
I have this JavaScript code:
function change(varam){
if(confirm("Select this option?"))
{
} else {
if(varam=="1")
{
alert("Return selected to NO");
} else {
alert("Return selected to YES");
}
}
}
And the HTML code:
<select id="sel" name="sel" onchange="change(this.value)">
<option value="1">YES</option>
<option value="0">NO</option>
</select>
What I want:
Suppose the selected default is YES. If the user selects NO, appear confirmation boxes if he wants to change to NO or not, if the choice is "OK", the option NO will be selected, if the choice is "CANCEL" then NO option is not selected, but back to the YES option are selected. And vice versa.
See this fiddle : http://jsfiddle.net/CtxUy/
Upvotes: 3
Views: 6091
Reputation: 817128
You can iterate over the options and select the one that has the selected
attribute. If none has it, select the first one (which is always the default in absence of the selected
attribute).
var select = document.getElementById('sel');
var options = select.options;
options[0].selected = true; // preemptively select the first option
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].hasAttribute('selected')) {
options[i].selected = true;
break;
}
}
Reference: HTMLSelectElement
, HTMLOptionElement
.
Upvotes: 1
Reputation: 191809
If you're only ever concerned about these two elements, you can just set the values manually:
if(varam=="1")
{
document.getElementById('sel').value = 0;
} else {
document.getElementById('sel').value = 1;
}
If there are potentially other values, what you can do is keep track of the initially selected value and set the selector value back to that when they refuse to confirm, or overwrite that stored value if they do confirm.
Like so: http://jsfiddle.net/CtxUy/2/
Upvotes: 1