如何使用jquery或javascript隐藏选择选项

9cbw7uwe  于 2022-12-18  发布在  jQuery
关注(0)|答案(3)|浏览(173)

我有以下两个选择框

<select id="first" onchange="hideShowOptions(this.value)">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

以及

<select id="second" >
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
</select>

以下是我的剧本

function hideShowOptions(selectedValue) {
    if(selectedValue == 1 || selectedValue == 2 || selectedValue == 3) {
        $('#second').children('option[value="8"]').css('display','none');
    } else {
        $('#second').children('option[value="8"]').css('display','inline');
    }
}


它按照上面的代码正确地设置了style="display: none",但是该选项没有从UI中隐藏,我仍然能够看到该选项。
目标是根据从first选择中选择的值,从second选择中隐藏特定选项。

kxkpmulp

kxkpmulp1#

以下是答案,承蒙导游

function hideShowOptions(selectedValue){
    if(selectedValue == 1 || selectedValue == 2 || selectedValue == 3)
    {
        $('#second').children('option[value="8"]').attr('disabled', ''); // if doesn't support will just disable
      //   $('#second').children('option[value="8"]').hide(); // if supports will hide
    }else{
        $('#second').children('option[value="8"]').removeAttr('disabled'); // if doesn't support will just enable
        //$('#second').children('option[value="8"]').show(); // if it supports, it will display
    }

}
bjp0bcyl

bjp0bcyl2#

<select id="first" onchange="hideShowOptions(this.value)">
                              <option value="1">1</option>
                              <option value="2">2</option>
                              <option value="3">3</option>
                              <option value="4">4</option>
 </select>

x一个一个一个一个x一个一个二个x

x6yk4ghg

x6yk4ghg3#

仅使用普通js:

const second = document.getElementById( "second")
const eight  = document.getElementById( "eight" )

function hideShowOptions( selectedValue ){
    if ( 
         selectedValue == 1 || 
         selectedValue == 2 || 
         selectedValue == 3
       ){
         eight.style.display = "none"
         second.value = 5 
           // prevents bug if user reselects 1,2 or 3
           // after selecting 8
        } else {
         eight.style.display = "inline"
        }
}
#eight {
  display: none
}
<select id="first" onchange="hideShowOptions(this.value)">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

<select id="second" >
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8" id="eight">8</option>
</select>

相关问题