jokul
jokul

Reputation: 1339

Dynamically alter displayed select text

I want to modify the selected index of a select element dynamically. Sometimes, options from selects will cause options in other selects to become disabled. I can disable the options just fine at run time on change, but I cannot alter the option that is displayed by the select.

For example, if I have this select:

<select>
    <option>Even or Odd?</option>
    <option>Even</option>
    <option>Odd</option>
</select>

<select>
    <option value="">Pick a Number</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option
</select>

When "Odd" is selected, the even numbers will be disabled, but if an even number was already selected when the first select was changed to "Odd" then even though the selected index for the second select is now 0, the displayed value is still the original value.

I have currently tried:

selects[i].selectedIndex = 0;
selects[i].value = "Pick a Number";
$(selects[i]).val("Pick a Number");
$(selects[i]).attrs("selectedIndex", 0);

The most that will happen is that the selected index will change or the value of the element will become an empty string without actually changing what is displayed on the page.

Upvotes: 0

Views: 86

Answers (1)

PSL
PSL

Reputation: 123739

Try setting it using prop and well there is no built in function named attrs unless you created one.

$(selects[i]).prop("selectedIndex", 0);

And your val should also work if you have value defined for your select option. (for the first one you dont have), for the second one just use .val(""). Pick a Number is not value of the option (instead it is "") it is the displayed text, but even though some browsers let you specify that as value (if value is not specified) i don't think that works across browsers. So always set value attribute for your options.

Also with what you are doing yuo can just do:

selects[i].value = "Even or Odd?"; //for your first one
selects[i].value = ""; //for your second one
selects[i].value = "Pick a Number"; //Wont work for second one because you are overriding with an empty value attribute.

Upvotes: 3

Related Questions