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

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

我怎么用这个。


当前回答

寻找jQuery站点

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
});

其他回答

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

<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

试试这个,

$('选择')。On ('change', function() { 警报(这。值); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <选择> <选项值= " 1 " > < / >选项之一 <选项值= " 2 " > 2 > < /选项 < /选择>

你也可以引用onchange event-

函数getval(选取) { 警报(sel.value); } <选择onchange = " getval(这个);" > <选项值= " 1 " > < / >选项之一 <选项值= " 2 " > 2 > < /选项 < /选择>

jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})

jQuery获取在Change事件上使用select html元素的值

演示和更多的例子

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

$('#select-id').change(function() {
    console.log($(this).val());
});