【问题标题】:jQuery get value of select onChangejQuery获取选择onChange的值
【发布时间】:2012-06-26 02:56:18
【问题描述】:

我的印象是,我可以通过执行此$(this).val(); 并将onchange 参数应用于选择字段来获取选择输入的值。

它似乎只有在我引用 ID 时才有效。

我该如何使用它。

【问题讨论】:

    标签: jquery select


    【解决方案1】:

    试试这个-

    $('select').on('change', function() {
      alert( this.value );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select>
        <option value="1">One</option>
        <option value="2">Two</option>
    </select>

    你也可以通过 onchange 事件来引用-

    function getval(sel)
    {
        alert(sel.value);
    }
    <select onchange="getval(this);">
        <option value="1">One</option>
        <option value="2">Two</option>
    </select>

    【讨论】:

    • 我知道这已经很晚了,但是如果您使用键盘(制表符)导航表单并使用向上/向下箭头从下拉列表中进行选择,那么 FireFox (22.0) 不会触发改变事件。您需要另外为 FireFox 绑定按键。附加信息:jQuery 1.10.2 使用语法 $('select').on('change', function(){ /* do seomthing */ });
    【解决方案2】:

    我的印象是我可以获得选择的价值 通过这样做 $(this).val();

    如果您不显眼地订阅(这是推荐的方法),则此方法有效:

    $('#id_of_field').change(function() {
        // $(this).val() will work here
    });
    

    如果您使用onselect 并将标记与脚本混合,您需要传递对当前元素的引用:

    onselect="foo(this);"
    

    然后:

    function foo(element) {
        // $(element).val() will give you what you are looking for
    }
    

    【讨论】:

      【解决方案3】:

      寻找 jQuery site

      HTML:

      <form>
        <input class="target" type="text" value="Field 1">
        <select class="target">
          <option value="option1" selected="selected">Option 1</option>
          <option value="option2">Option 2</option>
        </select>
      </form>
      <div id="other">
        Trigger the handler
      </div>
      

      JAVASCRIPT:

      $( ".target" ).change(function() {
        alert( "Handler for .change() called." );
      });
      

      jQuery 的例子:

      为所有文本输入元素添加有效性测试:

      $( "input[type='text']" ).change(function() {
        // Check input( $( this ).val() ) for validity here
      });
      

      【讨论】:

        【解决方案4】:

        尝试事件委托方法,这几乎适用于所有情况。

        $(document.body).on('change',"#selectID",function (e) {
           //doStuff
           var optVal= $("#selectID option:selected").val();
        });
        

        【讨论】:

          【解决方案5】:

          这对我有帮助。

          供选择:

          $('select_tags').on('change', function() {
              alert( $(this).find(":selected").val() );
          });
          

          对于单选/复选框:

          $('radio_tags').on('change', function() {
              alert( $(this).find(":checked").val() );
          });
          

          【讨论】:

            【解决方案6】:

            这对我有用。没有运气尝试了其他所有方法:

            <html>
            
              <head>
                <title>Example: Change event on a select</title>
            
                <script type="text/javascript">
            
                  function changeEventHandler(event) {
                    alert('You like ' + event.target.value + ' ice cream.');
                  }
            
                </script>
            
              </head>
            
              <body>
                <label>Choose an ice cream flavor: </label>
                <select size="1" onchange="changeEventHandler(event);">
                  <option>chocolate</option>
                  <option>strawberry</option>
                  <option>vanilla</option>
                </select>
              </body>
            
            </html>
            

            取自Mozilla

            【讨论】:

              【解决方案7】:

              你可以试试这个(使用jQuery)-

              $('select').on('change', function()
              {
                  alert( this.value );
              });
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
              
              <select>
                  <option value="1">Option 1</option>
                  <option value="2">Option 2</option>
                  <option value="3">Option 3</option>
                  <option value="4">Option 4</option>
              </select>

              或者你可以像这样使用简单的 Javascript-

              function getNewVal(item)
              {
                  alert(item.value);
              }
              <select onchange="getNewVal(this);">
                  <option value="1">Option 1</option>
                  <option value="2">Option 2</option>
                  <option value="3">Option 3</option>
                  <option value="4">Option 4</option>
              </select>

              【讨论】:

                【解决方案8】:
                $('#select_id').on('change', function()
                {
                    alert(this.value); //or alert($(this).val());
                });
                
                
                
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                
                <select id="select_id">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                    <option value="4">Option 4</option>
                </select>
                

                【讨论】:

                  【解决方案9】:

                  对于所有选择,调用此函数。

                  $('select').on('change', function()
                  {
                      alert( this.value );
                  });
                  

                  只有一个选择:

                  $('#select_id') 
                  

                  【讨论】:

                    【解决方案10】:

                    请注意,如果这些不起作用,可能是因为尚未加载 DOM 并且尚未找到您的元素。

                    要修复,请将脚本放在正文的末尾或使用准备好的文档

                    $.ready(function() {
                        $("select").on('change', function(ret) {  
                             console.log(ret.target.value)
                        }
                    })
                    

                    【讨论】:

                      【解决方案11】:
                      jQuery(document).ready(function(){
                      
                          jQuery("#id").change(function() {
                            var value = jQuery(this).children(":selected").attr("value");
                           alert(value);
                      
                          });
                      })
                      

                      【讨论】:

                        【解决方案12】:

                        箭头函数的作用域与函数不同, this.value 将给出未定义的箭头函数。 修复使用

                        $('select').on('change',(event) => {
                             alert( event.target.value );
                         });
                        

                        【讨论】:

                          【解决方案13】:

                          我想补充, 谁需要完整的自定义标题功能

                             function addSearchControls(json) {
                                  $("#tblCalls thead").append($("#tblCalls thead tr:first").clone());
                                  $("#tblCalls thead tr:eq(1) th").each(function (index) {
                                      // For text inputs
                                      if (index != 1 && index != 2) {
                                          $(this).replaceWith('<th><input type="text" placeholder=" ' + $(this).html() + ' ara"></input></th>');
                                          var searchControl = $("#tblCalls thead tr:eq(1) th:eq(" + index + ") input");
                                          searchControl.on("keyup", function () {
                                              table.column(index).search(searchControl.val()).draw();
                                          })
                                      }
                                      // For DatePicker inputs
                                      else if (index == 1) {
                                          $(this).replaceWith('<th><input type="text" id="datepicker" placeholder="' + $(this).html() + ' ara" class="tblCalls-search-date datepicker" /></th>');
                          
                                          $('.tblCalls-search-date').on('keyup click change', function () {
                                              var i = $(this).attr('id');  // getting column index
                                              var v = $(this).val();  // getting search input value
                                              table.columns(index).search(v).draw();
                                          });
                          
                                          $(".datepicker").datepicker({
                                              dateFormat: "dd-mm-yy",
                                              altFieldTimeOnly: false,
                                              altFormat: "yy-mm-dd",
                                              altTimeFormat: "h:m",
                                              altField: "#tarih-db",
                                              monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
                                              dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
                                              firstDay: 1,
                                              dateFormat: "yy-mm-dd",
                                              showOn: "button",
                                              showAnim: 'slideDown',
                                              showButtonPanel: true,
                                              autoSize: true,
                                              buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                                              buttonImageOnly: false,
                                              buttonText: "Tarih Seçiniz",
                                              closeText: "Temizle"
                                          });
                                          $(document).on("click", ".ui-datepicker-close", function () {
                                              $('.datepicker').val("");
                                              table.columns(5).search("").draw();
                                          });
                                      }
                                      // For DropDown inputs
                                      else if (index == 2) {
                                          $(this).replaceWith('<th><select id="filter_comparator" class="styled-select yellow rounded"><option value="select">Seç</option><option value="eq">=</option><option value="gt">&gt;=</option><option value="lt">&lt;=</option><option value="ne">!=</option></select><input type="text" id="filter_value"></th>');
                          
                                          var selectedOperator;
                                          $('#filter_comparator').on('change', function () {
                                              var i = $(this).attr('id');  // getting column index
                                              var v = $(this).val();  // getting search input value
                                              selectedOperator = v;
                                              if(v=="select")
                                                  table.columns(index).search('select|0').draw();
                                              $('#filter_value').val("");
                                          });
                          
                                          $('#filter_value').on('keyup click change', function () {
                                              var keycode = (event.keyCode ? event.keyCode : event.which);
                                              if (keycode == '13') {
                                                  var i = $(this).attr('id');  // getting column index
                                                  var v = $(this).val();  // getting search input value
                                                  table.columns(index).search(selectedOperator + '|' + v).draw();
                                              }
                                          });
                                      }
                                  })
                          
                              }
                          

                          【讨论】:

                            【解决方案14】:

                            jQuery 使用 on Change 事件获取选择的 html 元素的值

                            For Demo & More Example

                            $(document).ready(function () {   
                                $('body').on('change','#select_box', function() {
                                     $('#show_only').val(this.value);
                                });
                            }); 
                            <!DOCTYPE html>  
                            <html>  
                            <title>jQuery Select OnChnage Method</title>
                            <head> 
                             <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>    
                            </head>  
                            <body>  
                            <select id="select_box">
                             <option value="">Select One</option>
                                <option value="One">One</option>
                                <option value="Two">Two</option>
                                <option value="Three">Three</option>
                                <option value="Four">Four</option>
                                <option value="Five">Five</option>
                            </select>
                            <br><br>  
                            <input type="text" id="show_only" disabled="">
                            </body>  
                            </html>  

                            【讨论】:

                              【解决方案15】:

                              分享一个我用 BS4、thymeleaf 和 Spring boot 开发的例子。

                              我正在使用两个 SELECT,其中第二个(“子主题”)由基于第一个(“主题”)选择的 AJAX 调用填充。

                              首先,百里香sn-p:

                               <div class="form-group">
                                   <label th:for="topicId" th:text="#{label.topic}">Topic</label>
                                   <select class="custom-select"
                                           th:id="topicId" th:name="topicId"
                                           th:field="*{topicId}"
                                           th:errorclass="is-invalid" required>
                                       <option value="" selected
                                               th:text="#{option.select}">Select
                                       </option>
                                       <optgroup th:each="topicGroup : ${topicGroups}"
                                                 th:label="${topicGroup}">
                                           <option th:each="topicItem : ${topics}"
                                                   th:if="${topicGroup == topicItem.grp} "
                                                   th:value="${{topicItem.baseIdentity.id}}"
                                                   th:text="${topicItem.name}"
                                                   th:selected="${{topicItem.baseIdentity.id==topicId}}">
                                           </option>
                                       </optgroup>
                                       <option th:each="topicIter : ${topics}"
                                               th:if="${topicIter.grp == ''} "
                                               th:value="${{topicIter.baseIdentity.id}}"
                                               th:text="${topicIter.name}"
                                               th:selected="${{topicIter.baseIdentity?.id==topicId}}">
                                       </option>
                                   </select>
                                   <small id="topicHelp" class="form-text text-muted"
                                          th:text="#{label.topic.tt}">select</small>
                              </div><!-- .form-group -->
                              
                              <div class="form-group">
                                  <label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
                                  <select class="custom-select"
                                          id="subtopicsId" name="subtopicsId"
                                          th:field="*{subtopicsId}"
                                          th:errorclass="is-invalid" multiple="multiple">
                                      <option value="" disabled
                                              th:text="#{option.multiple.optional}">Select
                                      </option>
                                      <option th:each="subtopicsIter : ${subtopicsList}"
                                              th:value="${{subtopicsIter.baseIdentity.id}}"
                                              th:text="${subtopicsIter.name}">
                                      </option>
                                  </select>
                                  <small id="subtopicsHelp" class="form-text text-muted"
                                         th:unless="${#fields.hasErrors('subtopicsId')}"
                                         th:text="#{label.subtopics.tt}">select</small>
                                  <small id="subtopicsIdError" class="invalid-feedback"
                                         th:if="${#fields.hasErrors('subtopicsId')}"
                                         th:errors="*{subtopicsId}">Errors</small>
                              </div><!-- .form-group -->
                              

                              我正在遍历存储在模型上下文中的主题列表,显示所有组及其主题,然后显示所有没有组的主题。 BaseIdentity 是一个@Embedded 复合键顺便说一句。

                              现在,这是处理更改的 jQuery:

                              $('#topicId').change(function () {
                                  selectedOption = $(this).val();
                                  if (selectedOption === "") {
                                      $('#subtopicsId').prop('disabled', 'disabled').val('');
                                      $("#subtopicsId option").slice(1).remove(); // keep first
                                  } else {
                                      $('#subtopicsId').prop('disabled', false)
                                      var orig = $(location).attr('origin');
                                      var url = orig + "/getsubtopics/" + selectedOption;
                                      $.ajax({
                                          url: url,
                                         success: function (response) {
                                                var len = response.length;
                                                  $("#subtopicsId option[value!='']").remove(); // keep first 
                                                  for (var i = 0; i < len; i++) {
                                                      var id = response[i]['baseIdentity']['id'];
                                                      var name = response[i]['name'];
                                                      $("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
                                                  }
                                              },
                                              error: function (e) {
                                                  console.log("ERROR : ", e);
                                              }
                                      });
                                  }
                              }).change(); // and call it once defined
                              

                              change() 的初始调用确保它将在页面重新加载时执行,或者如果某个值已被后端的某些初始化预选。

                              顺便说一句:我正在使用“手动”表单验证(请参阅“is-valid”/“is-invalid”),因为我(和用户)不喜欢 BS4 将非必需的空字段标记为绿色。但这超出了此 Q 的范围,如果您有兴趣,我也可以发布。

                              【讨论】:

                                【解决方案16】:

                                仅适用于 JS

                                 let select=document.querySelectorAll('select') 
                                  select.forEach(function(el) {
                                    el.onchange =  function(){
                                     alert(this.value);
                                      
                                  }}
                                  )
                                

                                【讨论】:

                                  【解决方案17】:
                                  $('#select-id').change(function() {
                                      console.log($(this).val());
                                  });
                                  

                                  【讨论】:

                                  • 如果有人还需要获取选项的文本,这里是 $(this).find('option:selected').text();
                                  【解决方案18】:

                                  我有一个例子可以帮助你提出新的想法。 我希望这对任何人都有帮助。

                                  $('#editpricelist_box').change(function ($e){
                                      $('input[name="edit_unit_price"]').val(parseFloat(this.val()).toFixed(2));
                                      console.log(this.val());
                                  });
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 2011-10-06
                                    • 2012-04-11
                                    • 2011-12-14
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2012-10-22
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多