【问题标题】:Get selected value/text from Select on change从 Select on change 中获取选定的值/文本
【发布时间】:2011-03-24 08:54:43
【问题描述】:
<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

我需要在javascript中获取选定选项的值:有谁知道如何获取选定的值或文本,请告诉如何为它编写一个函数。我已经分配了 onchange() 函数来选择,那之后我该怎么办?

【问题讨论】:

标签: javascript


【解决方案1】:

为此使用 JavaScript 或 jQuery。

使用 JavaScript

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

使用 jQuery

$('#select_id').change(function(){
    alert($(this).val());
})

【讨论】:

  • .value() 适用于现代浏览器,但不适用于真正的旧浏览器。见bytes.com/topic/javascript/answers/…
  • @PlayHardGoPro 就是选择的值。如果你想要文本(例如 -Select- 或 Communication),你可以使用文本:select.text 或 jQuery select.text()。
  • 使用 jQuery $('#select_id option:selected').text() 。这将返回所选选项的文本,Select 或 Communication
  • 香草 javascript 方法:document.getElementById("select_id").onchange = (evt) =&gt; { console.log(evt.srcElement.value); }
  • 我不会依赖getElementById,因为您可能会对不同的选择使用相同的方法。如果你正在寻找的话,我会看看 YakovL 提出的答案。
【解决方案2】:

如果您在谷歌上搜索,并且不希望事件侦听器成为属性,请使用:

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});
<select id="my-select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

【讨论】:

    【解决方案3】:

    function test(a) {
        var x = (a.value || a.options[a.selectedIndex].value);  //crossbrowser solution =)
        alert(x);
    }
    <select onchange="test(this)" id="select_id">
        <option value="0">-Select-</option>
        <option value="1">Communication</option>
        <option value="2">Communication</option>
        <option value="3">Communication</option>
    </select>

    【讨论】:

    • a.value 是干什么用的?有没有真正支持这样的浏览器?我们不能只使用a.options[a.selectedIndex].value吗?
    • @Anonymous
    【解决方案4】:

    哇,答案中还没有真正可重用的解决方案。我的意思是,标准事件处理程序应该只获得一个 event 参数,并且根本不必使用 ids 。我会使用:

    function handleSelectChange(event) {
    
        // if you want to support some really old IEs, add
        // event = event || window.event;
    
        var selectElement = event.target;
    
        var value = selectElement.value;
        // to support really old browsers, you may use
        // selectElement.value || selectElement.options[selectElement.selectedIndex].value;
        // like el Dude has suggested
    
        // do whatever you want with value
    }
    

    您可以将此处理程序与每个内联 js 一起使用:

    <select onchange="handleSelectChange(event)">
        <option value="1">one</option>
        <option value="2">two</option>
    </select>
    

    jQuery:

    jQuery('#select_id').on('change',handleSelectChange);
    

    或原版 JS 处理程序设置:

    var selector = document.getElementById("select_id");
    selector.onchange = handleSelectChange;
    // or
    selector.addEventListener('change', handleSelectChange);
    

    并且不必为您拥有的每个 select 元素重写此内容。

    示例 sn-p:

    function handleSelectChange(event) {
    
        var selectElement = event.target;
        var value = selectElement.value;
        alert(value);
    }
    <select onchange="handleSelectChange(event)">
        <option value="1">one</option>
        <option value="2">two</option>
    </select>

    【讨论】:

    • 很好的解决方案,应该被接受。使用纯事件元素而不引用 DOM 文档是最灵活的方式,适用于 React、Vue 或纯 HTML 表单等多种环境。
    • 最佳解决方案!谢谢!
    【解决方案5】:

    不需要 onchange 函数。您可以在一行中获取值:

    document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;
    

    或者,为了更好的可读性,将其拆分:

    var select_id = document.getElementById("select_id");
    
    select_id.options[select_id.selectedIndex].value;
    

    【讨论】:

      【解决方案6】:
      let dropdown = document.querySelector('select');
      if (dropdown) dropdown.addEventListener('change', function(event) {
          console.log(event.target.value);
      });
      

      【讨论】:

      • 如果您使用箭头函数,这种方法很有帮助。
      • 任何箭头函数都可以用function() {}代替,都是一样的
      • 不一样。箭头函数中的this 从其词法环境中获取其上下文,但普通函数有其自己的 this。检查this
      • 啊,是的,我明白你的意思了。您可以将其存储在匿名函数之外的变量中,以确保您可以获得所需的正确范围
      【解决方案7】:

      HTML:

      <select onchange="cityChanged(this.value)">
            <option value="CHICAGO">Chicago</option>
            <option value="NEWYORK">New York</option>
      </select>
      

      JS:

      function cityChanged(city) {
          alert(city);
      }
      

      【讨论】:

        【解决方案8】:

        使用

        document.getElementById("select_id").selectedIndex
        

        或者获取值:

        document.getElementById("select_id").value
        

        【讨论】:

        • 这种获取值的方式在旧浏览器中不起作用,改用 Danny 的解决方案
        【解决方案9】:
        <script>
        function test(a) {
            var x = a.selectedIndex;
            alert(x);
        }
        </script>
        <select onchange="test(this)" id="select_id">
            <option value="0">-Select-</option>
            <option value="1">Communication</option>
            <option value="2">Communication</option>
            <option value="3">Communication</option>
        </select>
        

        在警报中,您将看到所选索引的 INT 值,将所选内容视为一个数组,您将获得该值

        【讨论】:

          【解决方案10】:

          我想知道每个人都发布了关于从&lt;option&gt; 获取的value 和text 选项,并且没有人建议label。

          所以我也建议label,因为所有浏览器都支持

          获取value(与其他人建议的相同)

          function test(a) {
          var x = a.options[a.selectedIndex].value;
          alert(x);
          }
          

          获取optiontext(即通讯或-Select-)

          function test(a) {
          var x = a.options[a.selectedIndex].text;
          alert(x);
          }
          

          OR(新建议)

          function test(a) {
          var x = a.options[a.selectedIndex].label;
          alert(x);
          }
          

          HTML

          <select onchange="test(this)" id="select_id">
              <option value="0">-Select-</option>
              <option value="1">Communication</option>
              <option value="2" label=‘newText’>Communication</option>
          </select>
          

          注意:在option 值 2 的上述 HTML 中,label 将返回 newText 而不是 Communication

          还有

          注意:在 Firefox 中不能设置 label 属性(只能返回)。

          【讨论】:

            【解决方案11】:

            为什么要过于复杂:

            var select = document.querySelector('[select#id.orClass]');
            select.addEventListener('change', function() {
              console.log(select.value);
            
              // or if it changes dynamically
              console.log(e.target.value);      
            });
            

             let select = document.getElementById('select_id');
              select.addEventListener('change', function() {
                console.log(select.value);
                // just for test
                alert(select.value);
              });
            <select id="select_id">
                <option value="0">-Select-</option>
                <option value="1">Communication</option>
            </select>

            【讨论】:

              【解决方案12】:

              这是一个老问题,但我不知道为什么人们不建议使用事件对象来检索信息,而不是再次通过 DOM 搜索。

              只需在 onChange 函数中遍历事件对象,请参见下面的示例

              function test() { console.log(event.srcElement.value); }

              http://jsfiddle.net/Corsico/3yvh9wc6/5/

              如果这不是 7 年前的默认行为,可能对今天查找此内容的人有用

              【讨论】:

                【解决方案13】:

                        $('#select_id').change(function(){
                        // selected value 
                        alert($(this).val());
                        // selected text 
                        alert($(this).find("option:selected").text());
                    })
                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
                <select onchange="test()" id="select_id">
                        <option value="0">-Select-</option>
                        <option value="1">Communication</option>
                    </select>

                【讨论】:

                  【解决方案14】:

                  function test(){
                    var sel1 = document.getElementById("select_id");
                    var strUser1 = sel1.options[sel1.selectedIndex].value;
                    console.log(strUser1);
                    alert(strUser1);
                    // Inorder to get the Test as value i.e "Communication"
                    var sel2 = document.getElementById("select_id");
                    var strUser2 = sel2.options[sel2.selectedIndex].text;
                    console.log(strUser2);
                    alert(strUser2);
                  }
                  <select onchange="test()" id="select_id">
                    <option value="0">-Select-</option>
                    <option value="1">Communication</option>
                  </select>

                  【讨论】:

                    【解决方案15】:

                    function test(){
                      var sel1 = document.getElementById("select_id");
                      var strUser1 = sel1.options[sel1.selectedIndex].value;
                      console.log(strUser1);
                      alert(strUser1);
                      // Inorder to get the Test as value i.e "Communication"
                      var sel2 = document.getElementById("select_id");
                      var strUser2 = sel2.options[sel2.selectedIndex].text;
                      console.log(strUser2);
                      alert(strUser2);
                    }
                    <select onchange="test()" id="select_id">
                      <option value="0">-Select-</option>
                      <option value="1">Communication</option>
                    </select>
                    var e = document.getElementById("ddlViewBy");
                    var strUser = e.options[e.selectedIndex].value;
                    

                    【讨论】:

                      【解决方案16】:

                      我试图用我自己的示例来解释,但我希望它会对你有所帮助。您不需要 onchange="test()" 请运行代码 sn-p 以获得实时结果。

                      document.getElementById("cars").addEventListener("change", displayCar);
                      
                      function displayCar() {
                        var selected_value = document.getElementById("cars").value;
                        alert(selected_value);
                      }
                      <select id="cars">
                        <option value="bmw">BMW</option>
                        <option value="mercedes">Mercedes</option>
                        <option value="volkswagen">Volkswagen</option>
                        <option value="audi">Audi</option>
                      </select>

                      【讨论】:

                      • 更改比点击事件好得多,因为选择一个选项不会致癌。
                      • @RileyCarney 好吧,这取决于,而不是根据 js 部分的函数名称更改来更改 ui 部分的重构代码,它更优雅,顺便说一句,我没有看到任何点击事件。
                      • 您对其进行了编辑以删除 onclick 事件哈哈。太阴暗了,在您单击之前,如果您单击汽车,则会收到通知。 edited 7 hours ago 至少你修复了不能正常工作的代码。
                      【解决方案17】:

                      您只需使用简单的老式 JavaScript 即可获得它。

                       <select onchange="test()" id="select_id">
                        <option value="0">-Select-</option>
                        <option value="1">Communication</option>
                       </select>
                      
                       function test()
                       {
                        let order_details_id=document.getElementById('select_id').value;
                        alert(select_id);
                       }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2022-01-16
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2017-11-09
                        • 1970-01-01
                        相关资源
                        最近更新 更多