简体   繁体   中英

How can I change the selected value of a dropdown list that uses opt groups?

I have a drop down list, which renders on the page like this:

<select id="DropDown">
    <optgroup label="">
        <option value="-1">
        </option>
    </optgroup>
    <optgroup label="Group 1">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
    </optgroup>
    <optgroup label="Group 2">
        <option value="11">Item 4</option>
        <option value="12">Item 5</option>
    </optgroup>
</select>

How can I use Javascript (with JQuery) to change the dropdown value? In past instances, I've iterated through the list of dropdown.options for the dropdown to find my desired value, and then set the select index based on that--but that option is not available to me with the optgroups there.

Dude, it's simple as this:

$('#id').val('the value you want to select');

In your example if you want to select:

<option value="2">Item 2</option>

Use this:

$('#DropDown').val('2');

You don't need to iterate anything, just assign the value and jQuery and the browser will do the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM