How to avoid re-creating jquery wrappers?

Is there a way to avoid using $("#check1") a second time in the instructions below?

 $("#check1").prop("checked",!$("#check1").prop("checked")); 

With some trick, can I do something like below?

 $("#check1").prop("checked",!this.prop("checked")); 
+4
source share
4 answers

If you pass the function as a callback, you will get the current value.

 $("#check1").prop("checked", function(i, value) { return !value; }); 

.prop( propertyName, function(index, oldPropertyValue) )

  • propertyNameThe name of the property to set.
  • function(index, oldPropertyValue) A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.

link

+5
source
 var el = $("#check1"); el.prop("checked",!el.prop("checked")); 
+3
source
 var $check = $("#check1"); $check.prop( "checked", !$check.prop("checked") ); 
+1
source

You can use this, but as follows:

 $("#check1").prop("checked",!$(this).prop("checked")); 
-2
source

All Articles