user2242044
user2242044

Reputation: 9213

jQuery .on() not working with multiple selectors

I have a form and am using jQuery to listen for and record changes by the user. It works great for either input or select fields, but does not seem to like combining them. Per the jQuery documentation on the .on() function, the selector should be a string. Looking around Stack Overflow, and it seems like 'select input' should work, but it is not. What is the correct way to use multiple selectors?

Full fiddle: http://jsfiddle.net/L55rvuqh/4/

Code in question:

$('#test').on('focusin', 'select input', function(){
    $(this).data('val', $(this).val());

}).on('change', 'select input', function(){

    var prev = $(this).data('val');
    var current = $(this).val();

    console.log("Prev value: " + prev);
    console.log("Current value: " + current);
});

Upvotes: 0

Views: 97

Answers (1)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

You should change it;

'select input'

to

'select,input'

$('#myform').on('focusin', 'select,input', function(){
    $(this).data('val', $(this).val());
    
}).on('change', 'select,input', function(){

    var prev = $(this).data('val');
    var current = $(this).val();
   
    console.log("Prev value: " + prev);
		console.log("Current value: " + current);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="myform">
        <input id="field1" type="text" />
        <select id="field2">
            <option>1</option>
            <option>2</option>
        </select>
</form>

Upvotes: 3

Related Questions