Call my function from JQUERY on click

I am trying to cut duplicate code in JQUERY, but I canโ€™t figure out how to call the function from the on-> click function.

My function looks like this:

function myCheckAll(div, closer, finder){ console.log(div+closer+finder); $(div).closest(closer).find(finder).prop('checked', this.checked); } 

And I'm trying to call it something like this

  $("#check_all_0").on('click', myCheckAll("#check_all_0", "table", "input#val0")); 

My problem is that it does not work. I dont understand what:

1) I define the function outside the brackets ready for the document. This is where I should define it?

2) When I load the page, the console log is called. Without clicking the target, and it does not call the function if I click on the target.

I am new to jquery and probably doing something completely wrong, but would appreciate any help. Thank you

+4
source share
4 answers
  $("#check_all_0").on('click', myCheckAll("#check_all_0", "table", "input#val0")); 

This will cause the first call to myCheckAll, and the result is passed as a jQuery event handler. You would need to wrap it with a function:

 $("#check_all_0").on('click', function() { myCheckAll("#check_all_0", "table", "input#val0")); }) 

Also see documentation

+2
source

You can use closure:

 $("#check_all_0").on('click', function() { myCheckAll("#check_all_0", "table", "input#val0"); }); 
+3
source

While the other answers work, I believe you are looking for something like this:

 $("input").on('click', {name: 'me'}, func); function func(event) { console.log(event.data.name); } 

Adapted to your code:

 $("#check_all_0").on('click', {div: "#check_all_0", closer: "table", finder: "input#val0"}, myCheckAll); function myCheckAll(event){ console.log(event.data.div); console.log(event.data.closer); console.log(event.data.finder); $(event.data.div).closest(event.data.closer).find(avent.data.finder).prop('checked', this.checked); } 

Demo: http://jsfiddle.net/nabil_kadimi/sdMQ2/

0
source

I'm not sure what you are trying to do, but this seems like checking the whole function, and so far this is not the answer to your question. This can help.

 $('#check_all_0').on('click',function(e){ $(this).closest('table').find(':checkbox').prop('checked',$(this).prop('checked')); }); 

Without viewing the HTML, it is impossible to find out if this is correct, but you use DOM identifiers to find things when perhaps this is not the best way.

0
source

Source: https://habr.com/ru/post/1496632/


All Articles