简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM