user984621
user984621

Reputation: 48483

Javascript - "is not a function" for parameter added to a function

I have this input:

<input type="checkbox" id="test_checkbox" onchange="fffunction(this)" /> Something

After checking/unchecking the checkbox is called the fffunction function:

function fffunction(checked_value) {
  if(checked_value.is(":checked")){
    console.log("checked");
  } else {              
    console.log("not checked");
  }
}

And this return an error that checked_value.is is not a function. How to check if the passed attribute is a function? How to use the parameter?

If I do this:

function fffunction(checked_value) {
      if($('#test_checkbox').is(":checked")){
        console.log("checked");
      } else {              
        console.log("not checked");
      }
    }

Everything's working... How to use the parameter, tho, instead of calling directly the ID HTML element inside the function?

Thank you in advance.

Upvotes: 0

Views: 35

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075059

You're trying to use a jQuery function on a raw DOM element. To do that, you have to wrap it in a jQuery instance first:

function fffunction(checked_value) {
  if($(checked_value).is(":checked")){
//   ^^-------------^---------------------- note
    console.log("checked");
  } else {              
    console.log("not checked");
  }
}

That's directly wrapping the element, not going by ID.


Of course, there's no reason to use jQuery in this particular case, just use the element's native checked property:

function fffunction(checked_value) {
  if(checked_value.checked){
    console.log("checked");
  } else {              
    console.log("not checked");
  }
}

Upvotes: 2

Related Questions