4

I have the following html code, and I am trying to set the value of option by selectedIndex. The problem is that the option is still displaying the old value whereas if I do an alert on what was selected it gives me the correct answer.

What am I missing?

<select name="select-choice-1" id="select-choice-1">
    <option value="none">Choose One</option>
    <option value="1">a</option>
    <option value="2">b</option>
    <option value="3">c</option>
    <option value="4">d</option>
</select>

<script>
    var HomeLocation = 1;
    document.getElementById("select-choice-1").selectedIndex = HomeLocation;
    alert(document.getElementById("select-choice-1").selectedIndex); // shows 1
</script>
5
  • 2
    how does it not work? This seems to work fine: jsfiddle.net/Lyn1mce0 Commented Oct 30, 2014 at 12:11
  • What browser is doing this and can you post a JsFiddle replicating the problem? Commented Oct 30, 2014 at 12:32
  • its on a tablet browser (android webview) Commented Oct 30, 2014 at 12:57
  • I wonder if this is a display bug. Try setting the visibility style to hidden, then an empty string on the next line. This should trigger a redraw of that element. Commented Oct 30, 2014 at 14:29
  • 2
    Are you maybe using some sort of script that "styles" the select element, e.g. jQuery Mobile, that requires refreshing/updating? Commented Nov 5, 2014 at 14:31

2 Answers 2

5

I've had inconsistent behavior with browsers. I usually have to set the selectedIndex and set the selected property of the <option>:

var select = document.getElementById("select-choice-1");
select.selectedIndex = 1;
select.options[1].selected = true;
Sign up to request clarification or add additional context in comments.

Comments

0

I was using JQuery Mobile and didn't realize that I had to refresh the element. This worked for me:

document.getElementById('select-choice-1').value = HomeLocation;
$("#select-choice-1").selectmenu("refresh");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.