当前位置: 动力学知识库 > 问答 > 编程问答 >

Using multiple jQuery selectors?

问题描述:

This is my example code:

<input type="text" id="input1" />

<input type="text" id="input2" />

<div id="result"></div>

And in jQuery I want to listen to both inputs change somehow like this:

$('#input1,#input2').change(function(){

var val1 = $('#input1').val();

var val2 = $('#input2').val();

[...some more code...]

});

but I just can't get it to work... Any help? Thanks in advance...

网友答案:

What doesn't work? See http://jsfiddle.net/XYSwz/

Html

<input type="text" id="input1" />
<input type="text" id="input2" />
<div id="result"></div>​

jQuery

$(document).ready(function() {
    $('#input1, #input2').change(function(){
        var val1 = $('#input1').val();
        var val2 = $('#input2').val();
    
        alert(val1);
        alert(val2);
    });​
});
网友答案:

Try this code:

$(document).ready(function() {
  $('#input1,#input2').change(function(){
    var val1 = $('#input1').val();
    var val2 = $('#input2').val();
     alert(val1);//test
     alert(val2);//test
  });
});

JSFIDDLE

网友答案:

Your code should function as is.

You could always try the add() function:

$(function() {
    $('#input1').add('#input2').change(function() {
        var val1 = $('#input1').val();
        var val2 = $('#input2').val();

    });
});

If your elements are created dynamically, you'll need to use the on() or live() function:

$(function() {
    $('#input1').add('#input2').on('change', function() {
        var val1 = $('#input1').val();
        var val2 = $('#input2').val();

    });
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: