简体   繁体   中英

Cannot select option with Javascript

I'm trying to select an option of a Dropdownlist using Javascript. My html Looks like the following:

<select id="active-drop" name="active">
    <option value="true">Aktiv</option>
    <option value="false"> Inaktiv </option> 
</select>

and my Javascript look like this:

$("#active-drop option[value='true']").attr("selected",true);
$("#active-drop option[value='false']").attr("selected",false);

The Problem here is, the Attribute is set just fine but the UI isn'z updated accordingly.

btw I already tried using selectedIndex but this yielded the same result(the data is set correctly but the UI isn't updated)

Try this:

<select id="active-drop" name="active">
    <option class="selected" value="true">Aktiv</option>
    <option value="false"> Inaktiv </option> 
</select>

And this

$(".selected").prop("selected",true);

As Tushar said:

 $('#active-drop [value="true"]').prop('selected', true); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="active-drop" name="active"> <option value="">Just to prove it</option> <option value="true">Aktiv</option> <option value="false"> Inaktiv </option> </select> 

try this one using Jquery:

 $('#active').val('ab'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="active" name="active"> <option value="ab">Aktiv</option> <option value="cs">Inaktiv</option> </select> 

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