0

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...

3
  • 2
    That should work fine. Have you placed your JavaScript code inside $(document).ready(function() { ... })? Commented Oct 17, 2012 at 10:03
  • This code should work. Where did you register this lines? in document.ready? Please make sure your HTML ids are 'input1' rendered in browser. Just checking view source will help Commented Oct 17, 2012 at 10:03
  • 1
    works just fine.. note that the change happens when the input box loses focus. (else you should uses the key events) Commented Oct 17, 2012 at 10:04

3 Answers 3

5

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);
    });​
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.