Most correct way to select option in <select> box

后端 未结 3 648
旧时难觅i
旧时难觅i 2021-01-21 05:13

I know there are multiple ways to select a particular option from a using jQuery:

  1. $select.val(\"someValue\")
  2. $option.attr(\"selected\"
3条回答
  •  自闭症患者
    2021-01-21 05:48

    $select.val("someValue")

    That's fine, in the common case where it's a non-multiple select and you don't have two different s with the same value. If that's the case I'd go with this, as the most readable option.

    $select[0].selectedIndex = 1

    That's more direct, so marginally quicker, and is necessary to be unambiguous for the case where you have multiple options with the same value.

    If you might have a multiple-select, you have to get/set the selectedness of each option separately:

    $select[0].options[1].selected= true;
    

    However:

    $option.attr("selected", "selected")

    Not generally the best approach. The problem with attr() is it's a nasty hack to access DOM properties and HTML attributes as if they are the same thing, trying to hide the difference from you. What attr() will do in this case is to set the selected DOM property, which is a boolean value. So attr('selected', true) would make more sense; 'selected' as a string value does also work, but only because all non-empty string values are ‘truthy’ in JavaScript.

    If you were actually setting the HTML selected attribute here, it would not have an effect on the selectedness of the option, because the selected attribute actually maps to the defaultSelected property and not selected! The selected property reflects the runtime form contents as altered by the user; defaultSelected reflects the actual attribute in the document containing the initial selectedness state.

    (Except on IE, due to a bug in its implementation of default values, and also in other browsers in some situations which are too intricate and confusing to go into. Take-home advice: don't try setting the selected HTML attribute from script as the results may be unpredictable. Work with the DOM properties. The same is also true of value/defaultValue for inputs and checked/defaultChecked for checkbox/radio.)

提交回复
热议问题