【问题标题】:Checking if an option in my form is selected won't work检查是否选择了我表单中的选项将不起作用
【发布时间】:2017-02-09 10:00:32
【问题描述】:

我正在尝试检查是否在我的表单中选择了一个选项(任何选项),尽管它不起作用。

我正在检查不是特别;这是我的代码:

if (document.getElementById('fillingtype') = selected;) {
  alert('yes');
} else {
  alert('no');
}
<select id="fillingtype" name="filling">
  <option id="tuna" value="tunamayo">Tuna Mayo</option>
  <option value="smokeychicken">Smokey Chicken + Crisp Lettuce</option>
  <option value="pizza">Meat Feast Pizza filling</option>
  <option value="hamcheese">Ham + Cheese</option>
</select>

我似乎无法让它工作,任何关于不同解决方案的建议将不胜感激。

【问题讨论】:

  • 语法错误:if (document.getElementById('fillingtype').selected) 单个 = 进行赋值,而不是比较,所以基本上你是在说“将我从文档中获得的 dom 元素设置为选定的变量”而不是“如果元素我从 DOm 得到的被选中,然后……'

标签: javascript forms html-select options


【解决方案1】:

我想总会有一个选定的值(默认情况下它将是 Tuna Mayo),您可以在用户选择这样的新值时添加一个侦听器:

document.getElementById('fillingtype').addEventListener('change',function(){ 
  console.log(this.value) 
});
<select id="fillingtype" name="filling">
  <option id="tuna" value="tunamayo">Tuna Mayo</option>
  <option value="smokeychicken">Smokey Chicken + Crisp Lettuce</option>
  <option value="pizza">Meat Feast Pizza filling</option>
  <option value="hamcheese">Ham + Cheese</option>
</select>

【讨论】:

    【解决方案2】:

    我们可以默认添加一个空值的非选项。

    <option selected value="">Please Select</option>
    

    如果值为空则表示用户没有选择任何选项:

    if(document.getElementById('fillingtype').value)
    

    您可以在此处查看示例:https://jsfiddle.net/mpad/8es6eunm/4/

    【讨论】:

      【解决方案3】:
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      </head>
      <body>
      <form>
      <select id="fillingtype" name="filling">
        <option value="tunamayo">Tuna Mayo</option>
        <option value="smokeychicken">Smokey Chicken + Crisp Lettuce</option>
        <option value="pizza">Meat Feast Pizza filling</option>
        <option value="hamcheese">Ham + Cheese</option>
      </select>
         </form>
      
      <script>
      $( "#fillingtype" ).change(function() {
      alert($( "#fillingtype option:selected" ).text());
      });
      </script>
      </body>
      </html>
      

      http://jsbin.com/tikifi/1/edit?html,js,console,output

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-28
        • 1970-01-01
        • 2012-09-13
        • 2023-03-24
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多