How to add “selected” in option attribute using Javascript or jQuery?

后端 未结 6 907
猫巷女王i
猫巷女王i 2021-02-09 02:16

Below is code for select option and generate using php from database and i try to add selected=\"selected\" to value=\"4\" using jQuery or any javascri

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 02:54

    The selected attribute is a boolean attribute, its presence sets the value of the related DOM property to true. If the attribute is absent, the value of the selected property is false.

    If an option has the selected attribute, then when the page is first loaded, or the form the control is in is reset, that option will be the selected option.

    If the option's selected property is set to true, then that option will be selected. However, if the form is reset, the default selected option will be selected (i.e. the one with the selected attribute, or the first option, or none).

    To set the selected attribute (i.e. make the option the default selected option):

    var select = document.getElementById('countryselect');
    var option;
    
    for (var i=0; i

    Note that this may not make the option the currently selected option, it will just add the selected attribute. To make sure it's selected (if that is what is required), the also set the selected property to true (see below).

    Note that the second argument to setAttribute is supposed to be a string that is used to set the attribute's value. However, the selected attribute doesn't have a "setable" value, so the second argument is ignored (e.g. even false will still set the attribute and make the option the default selected option). That causes some confusion. :-)

    To set the selected property (i.e. just make the option the current selected option):

    var select = document.getElementById('countryselect');
    var option;
    
    for (var i=0; i

提交回复
热议问题