【问题标题】:How can I disable an <option> in a <select> based on its value in JavaScript?如何根据 JavaScript 中的值禁用 <select> 中的 <option>?
【发布时间】:2011-01-10 11:39:04
【问题描述】:

我有一个&lt;select&gt; 和多个&lt;option&gt;s。每个都有独特的价值。我需要使用给定的定义值(不是 innerhtml)禁用&lt;option&gt;

有人知道怎么做吗?

【问题讨论】:

标签: javascript html select


【解决方案1】:

JavaScript,2022 年

您可以在 2022 年使用生成的 NodeList 中的 querySelectorAll 和 forEach 更轻松地完成相同的操作。

document.querySelectorAll("#foo option").forEach(opt => {
    if (opt.value == "StackOverflow") {
        opt.disabled = true;
    }
});

不过,请注意字符串比较。 'StackOverflow' 和 'stackoverflow' 不是同一个字符串。因此,您可以在比较之前对字符串调用 .toLowerCase(),甚至可以使用不区分大小写的正则表达式比较,如下所示:

if ( /^stackoverflow$/i.test(option.value) ) {
  option.disabled = true;
}

纯 Javascript (2010)

使用纯 Javascript,您必须循环浏览每个选项,并单独检查它的值。

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

不启用非目标元素:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

###jQuery

使用 jQuery,您可以用一行代码完成:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

不启用非目标元素:

$("option[value='stackoverflow']").attr("disabled", "disabled");

​ 请注意,此 不是 不区分大小写的。 “StackOverflow”将不等于“stackoverflow”。要获得不区分大小写的匹配,您必须循环遍历每个,将值转换为小写,然后检查:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

不启用非目标元素:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

【讨论】:

  • 不,对于值,您将使用 $("option[value=someval]")。他在寻找价值,而不是里面的文字。
  • 啊,好点子,@KyleButt。我已经更新了我的解决方案。感谢您指出这一点。
  • 禁用带有“stackoverflow”的选项并不意味着启用那些没有“stackoverflow”的选项。
  • @Gumbo:正确。我试图预测未来的问题,但我可以看到我的解决方案将如何导致更多问题,例如用户是否默认禁用了 other 选项。我已经更新了我的解决方案。感谢您指出我的错误。
  • op[i].disabled = (op[i].value.toLowerCase() == "stackoverflow") ;) +1
【解决方案2】:

你也可以使用这个功能,

function optionDisable(selectId, optionIndices)
{
    for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
    {
        document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
        document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
        document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
    }
}

【讨论】:

  • 我已经格式化了代码,但是这个函数的其他问题需要你来解决。 :P
【解决方案3】:

为选项设置一个 id,然后使用按 id 获取元素并在选择 x 值时禁用它..

例子

<body>
      <select class="pull-right text-muted small" 
                 name="driveCapacity" id=driveCapacity onchange="checkRPM()">
      <option value="4000.0" id="4000">4TB</option>
      <option value="900.0" id="900">900GB</option>
      <option value="300.0" id ="300">300GB</option>
    </select>
    </body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){         
        document.getElementById("driveCapacity").value = "4000.0";
        document.getElementById("4000").disabled = false;           
    }else{          
        document.getElementById("4000").disabled = true;            
    }    
</script>

【讨论】:

    【解决方案4】:
    var vals = new Array( 2, 3, 5, 8 );
    select_disable_options('add_reklamaciq_reason',vals);
    select_disable_options('add_reklamaciq_reason');
    
    function select_disable_options(selectid,vals){
      var selected = false ;
      $('#'+selectid+' option').removeAttr('selected');
      $('#'+selectid+' option').each(function(i,elem){
           var elid = parseInt($(elem).attr('value'));
           if(vals){
               if(vals.indexOf(elid) != -1){
                   $(elem).removeAttr('disabled');
                   if(selected == false){
                       $(elem).attr('selected','selected');
                       selected = true ; 
                   }
               }else{
                   $(elem).attr('disabled','disabled'); 
               }
           }else{
                $(elem).removeAttr('disabled');
           }
      });   
    }
    

    这里有JQ ..如果有人搜索它

    【讨论】:

      【解决方案5】:

      我还想给你一个想法,用给定的定义值 (not innerhtml) 禁用 &lt;option&gt;。我建议使用jQuery 来获得最简单的方法。请参阅下面的示例。

      HTML

      Status:  
      <div id="option">
         <select class="status">
            <option value="hand" selected>Hand</option>
            <option value="simple">Typed</option>
            <option value="printed">Printed</option>
         </select>
      </div>
      

      Javascript

      这里的想法是当当前StatusHand 时如何禁用Printed 选项

      var status = $('#option').find('.status');//to get current the selected value
      var op = status.find('option');//to get the elements for disable attribute
      (status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
      

      你可以在这里看到它是如何工作的:

      https://jsfiddle.net/chetabahana/f7ejxhnk/28/

      【讨论】:

        【解决方案6】:

        由于某些原因,其他答案不必要地复杂,用纯 JavaScript 一行很容易做到:

        Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;
        

        selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;
        

        性能取决于选项的数量(选项越多,第一个越慢)以及是否可以从第二个中省略escapingreplace 调用)。第一个也使用了Array.find 和 IE11 中不可用的箭头函数。

        【讨论】:

          【解决方案7】:

          使用简单的选择器:

          document.querySelector('select[name="theName"] option[value="theValue"]').disabled = true;

          【讨论】:

            猜你喜欢
            • 2020-08-19
            • 1970-01-01
            • 2018-12-16
            • 2021-12-15
            • 2014-10-11
            • 2020-03-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多