How to change selected item in jQuery

This question already has an answer here:

  • Change the selected value of a drop-down list with jQuery 15 answers

  • I think your first try was the right try.

     $('#slc').val('3');
    

    It does seem to work: https://jsfiddle.net/crix/hdtndzkb/

    Did you include the jquery library right? Does your code gets hit? Just try to see if it does by add a console.log() entry.


    $("#slc option[value=3]").prop('selected', 'selected');//get option with value 3 and set selected
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <select id="slc">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>

    When do you fire the code? Maybe you should just wrap it in a document.ready function? I made this, and it works like a charm: https://jsfiddle.net/41bna2e9/

    $(document).ready(function(){
        $("#slc").val("2");
    });
    

    Hope that it helps!

    链接地址: http://www.djcxy.com/p/83906.html

    上一篇: 如何通过javascript在下拉菜单中设置选定的值

    下一篇: 如何在jQuery中更改选定的项目