【问题标题】:when using javascript how do you use select form to do if else statements?使用 javascript 时如何使用 select 表单来执行 if else 语句?
【发布时间】:2010-03-09 07:30:40
【问题描述】:

如何在选择表单中获取选项的值并将其用于 if else 语句?

例如,如果选择了苹果作为选项,则在文档中写入如何制作苹果酱但选择了橙子,然后写入如何制作橙子?

到目前为止,我有一个基本的表单和选择选项,并且我知道如何执行 document.write,但我不知道如何将选择表单与 if else 一起使用

感谢您的帮助

【问题讨论】:

    标签: javascript select if-statement


    【解决方案1】:

    首先,确保您的<select> 上有一个id,允许您从Javascript 中引用它:

    <select id="fruits">...</select>
    

    现在,您可以在 &lt;select&gt; 的 Javascript 表示中使用 optionsselectedIndex 字段来访问当前选定的值:

    var fruits = document.getElementById("fruits");
    var selection = fruits.options[fruits.selectedIndex].value;
    
    if (selection == "apple") {
        alert("APPLE!!!");
    }
    

    【讨论】:

      【解决方案2】:
      var select = document.getElementById('myList');
      if (select.value === 'apple') {
        /* Applesauce */
      } else if (select.value === 'orange') {
        /* Orange */
      }

      【讨论】:

        【解决方案3】:

        您的 HTML 标记

        <select id="Dropdown" >
            <option value="Apple">Apple</option>
            <option value="Orange">Orange</option>
        </select>
        

        你的 JavaScript 逻辑

        if(document.getElementById('Dropdown').options[document.getElementById('Dropdown').selectedIndex].value == "Apple") {
        //write applesauce
        }
        else {
        //everything else
        }
        

        【讨论】:

        • 我认为你在混合。看起来您正在使用 jQuery-ish 选择器函数,但您只是编写了“if('#Dropdown')”。此外,尽可能使用 ===
        • 抱歉,已修复。当我想到 JavaScript 时,我想到了 jQuery。
        【解决方案4】:

        您也可以这样做。

        var fruitSelection = document.formName.optionName; /* if select has been given an name AND a form have been given a name */
        /* or */ 
        var fruitSelection = document.getElementById("fruitOption"); /* If <select> has been given an id */
        
        var selectedFruit = fruitSelection.options[fruitSelection.selectedIndex].value;
        
        if (selectedFruit == "Apple") {
          document.write("This is how to make apple sauce....<br />...");
        } else {
        
        }
        

        //HTML

        <!-- For the 1st option mentioned above -->
        
        <form name="formName">
          <select name="optionName> <!-- OR -->
          <select id="optionName">
            <option value="Apple">Apple</option>
            <option value="Pear">Pear</option>
            <option value="Peach">Peach</option>
          </select>
        </form>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-11
          • 1970-01-01
          • 2015-05-16
          • 1970-01-01
          • 2014-02-15
          • 2013-03-13
          • 2022-07-28
          • 1970-01-01
          相关资源
          最近更新 更多