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

只有在引用ID时,它才会起作用。

我怎么用这个。


当前回答

$('#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>

其他回答

这对我来说很管用。我尝试了其他所有方法,但都没有成功:

<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

只使用JS

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

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

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

这对我有帮助。

选择:

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

For radio / checkbox:

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