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

前端 未结 21 1964
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);
    });
    
    
    
    

    Props to the good stuff ;)


    Attributing the bad stuff to attr

    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.

提交回复
热议问题