Reputation:
I am trying to write a generic code
var rodd = $('#checkBox');
I want to pass rodd to a function and check if it is checked
Callme(rodd);
$(rodd).click(function() {
Callme(this);
});
function Callme(rodd){
if(this.checked){
// do some behavior
}
}
Upvotes: 23
Views: 61911
Reputation: 125488
Looking at your code, your passing in a jQuery object, rodd
, into a function to return a jQuery object $(rodd).click...
It might be easier to do
$('#checkBox').click(Callme);
function Callme(rodd){
if(this.checked){
// do some behavior
}
}
or
$('#checkBox').click(Callme);
function Callme(rodd){
if($(this).is(':checked')){
// do some behavior
}
}
this also does away with the anonymous function event handler that is only executing Callme()
passing in the event target. Working Demo here.
EDIT:
Currently, Callme(rodd)
above expects a HTMLElement object
to be passed in. If you want to be able to pass in a jQuery object, simply change to this
$('#checkBox').click(function(event) {
Callme($(event.target));
});
function Callme(rodd){
if(rodd.is(':checked')){
alert('checked');
}
}
although personally, I would keep it as an element to be passed in and do the wrapping in the Callme
function. you might want to consider prefixing the rodd
parameter with $
to make it obvious that a jQuery object is expected.
Upvotes: 2
Reputation: 58911
This should work:
//Assuming rodd is a jquery element
Callme(rodd);
rodd.click(function() {
Callme($(this));
});
function Callme(rodd){
if(this.is(":checked"){
// do some behavior
}
}
remember that the event listener has this pointing at the DOM element, not the jquery element. Therefore you need to convert this into a jquery element, using the $(this) expression.
Upvotes: 5
Reputation: 625027
If rodd
is a jQuery object:
function Callme(rodd) {
if (rodd.is(":checked")) {
// ...
}
}
or:
function Callme(rodd) {
if (rodd[0].checked) {
// ...
}
}
Upvotes: 18