简体   繁体   中英

Issue on Setting HTML Select Option Using jQuery

I am trying to change selected item from the list options dynamically at This Demo but it is not working.

<select id="selItems" class="selectpicker">
    <option>Select From List</option>
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
</select>
<p>
<button id="setdefault" type="submit" class="btn">Set Default</button>

<script>
 $("#setdefault").on("click", function () {
   $("#selItems option:eq(2)").attr("selected", "selected");
 });
</script>

can you please let me know what I am doing wrong?

Bootstrap Select has a method for doing this. You shouldn't be manually manipulating attributes because the element seen in the page isn't the original select element anyway.

$("#setdefault").on("click", function () {
    $("#selItems").selectpicker('val', 'Ketchup');
});

Demo

http://silviomoreto.github.io/bootstrap-select/#methods

There are several reasons why your code is not working how you expect it to.

You are setting a click event on your select element, and not on the "set default" button.

Your actual select element is not visible on the page because it is being replaced by the jquery plugin you are using.. so even if you set the selected attribute of your select, you won't see it on the page.

You should refer to the documentation of that plugin to figure out how it is used.

Try using prop instead of attr :

  $("#setdefault").on("click", function () { $("#selItems option:eq(2)").prop("selected", true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="selItems" class="selectpicker"> <option>Select From List</option> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> <p> <button id="setdefault" type="submit" class="btn">Set Default</button> 

Try switching

$("#setdefault").on("click",function(){
 $("#selItems option:eq(3)").attr("selected", "selected");
});

to

$("#setdefault").on("click",function(){
 $("#setdefault option:eq(3)").attr("selected", "selected");
});

Just use val() :

 $("#setdefault").on("click", function() { $("#selItems").val("Mustard"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="selItems" class="selectpicker"> <option>Select From List</option> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> <p> <button id="setdefault" type="submit" class="btn">Set Default</button> 

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