Skip to content

bobby_dreamer

JQuery - checkbox, calling functions and automatic passing of this

jquery, javascript1 min read

Scenario : Say using JQuery, i am listening to events on a webpage under class page > adminSwitch and page > premiumSwitch.

And whats new to me is, till this point i did'nt know with jQuery you can do something like this, say when we use $(this), it means we are refering to the element that triggered the event. In that triggered function, we can use $(this) to refer to the element. What i didn't know is, we can call another function and don't have to pass $(this) to it as jQuery does this automatically and refer the element that triggered the event.

1//jQuery will automatically invoke function with the proper context set
2//meaning no need to pass $(this).
3$('.page').on('click', '.adminSwitch', getSwitchValues);
4$('.page').on('click', '.premiumSwitch', getSwitchValues);

This is the function getSwitchValues is defined before the above two statements. Notice the highlighted statement $(this) here refers to the toggle switch which triggered the event.

1function getSwitchValues(){
2 let classname = $(this).attr('class');
3 console.log(classname);
4
5 let uid = $(this).attr('content');
6 console.log(uid);
7
8 let cbAdminSwitch=null, cbPremiumSwitch=null;
9 if(classname =="adminSwitch"){
10 cbAdminSwitch = $(this).prop('checked');
11 //This goes up(closest) and next() and finds the class and checks the property
12 cbPremiumSwitch = $(this).closest('td').next().find('.premiumSwitch').prop('checked');
13 }else{
14 cbPremiumSwitch = $(this).prop('checked');
15 //This goes up(closest) and next() and finds the class and checks the property
16 cbAdminSwitch = $(this).closest('td').prev().find('.adminSwitch').prop('checked');
17 }
18
19 console.log(cbAdminSwitch);
20 console.log(cbPremiumSwitch);
21 updateClaims(uid, cbAdminSwitch, cbPremiumSwitch);
22 }