简体   繁体   中英

Select a select option element without a “selected” attribute

So here is the thing:

I have a java app and it creates a group of selects based on a db. Also, if it happens that an element (let's call it product) has that value, it print the option with the selected attribute.

<select>
    <option value="1">text1</option>
    <option value="2" selected>text2</option>
    <option value="3">text3</option>
    <option value="4">text4</option>
    <option value="5">text5</option>
</select>
<select>
    <option value="1">text1</option>
    <option value="2">text2</option>
    <option value="3">text3</option>
</select>
<select>
    <option value="1">text1</option>
    <option value="2">text2</option>
</select>

What i want to do is set in blank (set a value of zero) to the selects that not has an element with a selected value.

If you know another form to set to blank a list (diferent from put a default empty element in every select), please let me know.

Demo $('option:not(:selected)').val(0); use :not and :selected and set the value to 0

The way to do this without an empty option, is to set the selectedIndex to -1

$('select:not(:has(option[selected]))').prop("selectedIndex", -1);

FIDDLE

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