How do you select a particular option in a SELECT element in jQuery?

前端 未结 21 1768
Happy的楠姐
Happy的楠姐 2020-11-22 10:55

If you know the Index, Value or Text. also if you don\'t have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

相关标签:
21条回答
  • 2020-11-22 11:19

    There are a few suggestions why you should use prop instead of attr. Definitely use prop as I've tested both and attr will give you weird results except for the simplest of cases.

    I wanted a solution where selecting from an arbitrarily grouped select options automatically selected another select input on that same page. So for instance, if you have 2 dropdowns - one for countries, and the other for continents. In this scenario, selecting any country automatically selected that country's continent on the other continent dropdown.

    $("#country").on("change", function() {
      //get continent
      var originLocationRegion = $(this).find(":selected").data("origin-region");
    
      //select continent correctly with prop
      $('#continent option[value="' + originLocationRegion + '"]').prop('selected', true);
    });
    
    
    
    $("#country2").on("change", function() {
      //get continent
      var originLocationRegion = $(this).find(":selected").data("origin-region");
    
      //select continent wrongly with attr
      $('#continent2 option[value="' + originLocationRegion + '"]').attr('selected', true);
    });
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="container">
      <form>
        <h4 class="text-success">Props to the good stuff ;) </h4>
        <div class="form-row">
          <div class="form-group col-md-6 col-sm-6">
            <label>Conuntries</label>
            <select class="custom-select country" id="country">
              <option disabled selected>Select Country </option>
              <option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
              <option data-origin-region="Antartica" value="Antartica">Antartica</option>
              <option data-origin-region="Australia" value="Australia">Australia</option>
              <option data-origin-region="Europe" value="Austria">Austria</option>
              <option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
              <option data-origin-region="South America" value="Brazil">Brazil</option>
              <option data-origin-region="Africa" value="Cameroon">Cameroon</option>
              <option data-origin-region="North America" value="Canada">Canada</option>
              <option data-origin-region="South America" value="Chile">Chile</option>
              <option data-origin-region="Asia" value="China">China</option>
              <option data-origin-region="South America" value="Ecuador">Ecuador</option>
              <option data-origin-region="Australia" value="Fiji">Fiji</option>
              <option data-origin-region="North America" value="Mexico">Mexico</option>
              <option data-origin-region="Australia" value="New Zealand">New Zealand</option>
              <option data-origin-region="Africa" value="Nigeria">Nigeria</option>
              <option data-origin-region="Europe" value="Portugal">Portugal</option>
              <option data-origin-region="Africa" value="Seychelles">Seychelles</option>
              <option data-origin-region="North America" value="United States">United States</option>
              <option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
            </select>
          </div>
          <div class="form-group col-md-6 col-sm-6">
            <label>Continent</label>
            <select class="custom-select" id="continent">
              <option disabled selected>Select Continent</option>
              <option disabled value="Africa">Africa</option>
              <option disabled value="Antartica">Antartica</option>
              <option disabled value="Asia">Asia</option>
              <option disabled value="Europe">Europe</option>
              <option disabled value="North America">North America</option>
              <option disabled value="Australia">Australia</option>
              <option disabled value="South America">South America</option>
            </select>
          </div>
        </div>
      </form>
      <hr>
    
      <form>
        <h4 class="text-danger"> Attributing the bad stuff to attr </h4>
        <div class="form-row">
          <div class="form-group col-md-6 col-sm-6">
            <label>Conuntries</label>
            <select class="custom-select country-2" id="country2">
              <option disabled selected>Select Country </option>
              <option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
              <option data-origin-region="Antartica" value="Antartica">Antartica</option>
              <option data-origin-region="Australia" value="Australia">Australia</option>
              <option data-origin-region="Europe" value="Austria">Austria</option>
              <option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
              <option data-origin-region="South America" value="Brazil">Brazil</option>
              <option data-origin-region="Africa" value="Cameroon">Cameroon</option>
              <option data-origin-region="North America" value="Canada">Canada</option>
              <option data-origin-region="South America" value="Chile">Chile</option>
              <option data-origin-region="Asia" value="China">China</option>
              <option data-origin-region="South America" value="Ecuador">Ecuador</option>
              <option data-origin-region="Australia" value="Fiji">Fiji</option>
              <option data-origin-region="North America" value="Mexico">Mexico</option>
              <option data-origin-region="Australia" value="New Zealand">New Zealand</option>
              <option data-origin-region="Africa" value="Nigeria">Nigeria</option>
              <option data-origin-region="Europe" value="Portugal">Portugal</option>
              <option data-origin-region="Africa" value="Seychelles">Seychelles</option>
              <option data-origin-region="North America" value="United States">United States</option>
              <option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
            </select>
          </div>
          <div class="form-group col-md-6 col-sm-6">
            <label>Continent</label>
            <select class="custom-select" id="continent2">
              <option disabled selected>Select Continent</option>
              <option disabled value="Africa">Africa</option>
              <option disabled value="Antartica">Antartica</option>
              <option disabled value="Asia">Asia</option>
              <option disabled value="Europe">Europe</option>
              <option disabled value="North America">North America</option>
              <option disabled value="Australia">Australia</option>
              <option disabled value="South America">South America</option>
            </select>
          </div>
        </div>
      </form>
    </div>

    As seen in the code snippet, prop works correctly every time, but attr fails to select properly once the option has been selected once.

    Keypoint: We're usually interested in the property of the attribute, so its safer to use prop over attr in most situations.

    0 讨论(0)
  • 2020-11-22 11:21

    None of the methods above provided the solution I needed so I figured I would provide what worked for me.

    $('#element option[value="no"]').attr("selected", "selected");
    
    0 讨论(0)
  • 2020-11-22 11:21

    By value, what worked for me with jQuery 1.7 was the below code, try this:

    $('#id option[value=theOptionValue]').prop('selected', 'selected').change();
    
    0 讨论(0)
  • 2020-11-22 11:23

    Exactly it will work try this below methods

    For normal select option

    <script>    
        $(document).ready(function() {
        $("#id").val('select value here');
           });
            </script>
    

    For select 2 option trigger option need to use

    <script>    
            $(document).ready(function() {
            $("#id").val('select value here').trigger('change');
               });
                </script>
    
    0 讨论(0)
  • 2020-11-22 11:23

    For setting select value with triggering selected:

    $('select.opts').val('SEL1').change();
    

    For setting option from a scope:

    $('.selDiv option[value="SEL1"]')
        .attr('selected', 'selected')
        .change();
    

    This code use selector to find out the select object with condition, then change the selected attribute by attr().


    Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.

    0 讨论(0)
  • 2020-11-22 11:23
    /* This will reset your select box with "-- Please Select --"   */ 
        <script>
        $(document).ready(function() {
            $("#gate option[value='']").prop('selected', true);
        });
        </script>
    
    0 讨论(0)
提交回复
热议问题