Home > Software design >  TypeError: checked is not a function at HTMLInputElement.onchange
TypeError: checked is not a function at HTMLInputElement.onchange

Time:03-14

I've had a problem where I wrote a checked() function for the onchange of a checkbox:

<input
      type="checkbox"
      id = "checked"
      onchange="checked()"
    />

Here's my javascript:

const check = document.getElementById("checkbox")
const yes = document.getElementsByClassName("yes")

function checked() {
  if (check.checked) {
    yes.innerHTML = "Yes"
  } else {
    yes.innerHTML = "No"
  }
}

Basically I want the span with the class of yes to change output depending on if the checkbox is checked or not (Says Yes or No) However, when I inspect, it says "TypeError: checked is not a function at HTMLInputElement.onchange" even though my javascript is perfectly linked to my HTML (I checked this with an alert).

How can I solve this?

CodePudding user response:

You're getting checkbox by id checkbox, but in your input field, you put id="checked" which is incorrect, so you need to correct your id from checked to checkbox.

<input
      type="checkbox"
      id = "checkbox"
      onchange="checked()"
    />

You also need to change your function name from checked to another name (like checkData which is not similar with native values/functions) and then wrap your document.getElementById into your function

You should not use getElementsByClassName too, because it returns a list of elements and innerHTML does not work for those, so you need to select a particular element with getElementById

function checkData() {
  const check = document.getElementById("checkbox")
  const yes = document.getElementById("yes") //need to use `getElementById` instead of `getElementsByClassName`
  if (check.checked) {
    yes.innerHTML = "Yes"
  } else {
    yes.innerHTML = "No"
  }
}

Remember to implement your yes element like this

<p id="yes"></p> //tag name is your choice

Technically, checked is the name of the value attribute on that input and it's not a function, so you cannot use it as a function name.

By the way, thank @Teemu for the suggestion!

CodePudding user response:

const check = document.getElementById("checkbox")

There is no such ID in your code named "checkbox". I think you want:

const check = document.getElementById("checked")

Try giving your IDs, function names and input-types unique names so you won't get them mixed up with each other.

  • Related