JavaScript: Is there a reason that console.log works but not return?

2.1k views Asked by At

I am trying to get a checkbox to return 1 or 0 depending upon if it is checked or not. I am having a hard time understanding why the return in this if function is not working. If I used console.log instead of return the output is correct. 1 when checked 0 when unchecked. with return, checked is skipped and it only returns the else statement, so it is 0 either checked or unchecked. I am new to coding in general so I am sure I am missing something simple here. Any ideas? Thanks!

document.getElementById("materialLoaded").addEventListener('input', materialCheck);

function materialCheck() {

    if (this.checked) {
        return 1;
    } else {
        return 0;
    }
}
2

There are 2 answers

2
Milad Deraawi On

sure thing you won't be seeing anything because ur not telling your program to tell u anything. you're telling it to return a value In a function but to see the value it returned u have to call the function. for example to see ur return value call the function using your window:

 document.getElementById("materialLoaded").addEventListener('input', materialCheck);

function materialCheck() {

if (this.checked) {
    return 1;
} else {
    return 0;
}

window.alert(materialCheck());
 }

javascript is object oriented, u can't write a function and it should work by itself, it has to be called. console.log works because there's an object there which is the console calling the function for example or displaying what u asked for(ex: console.log("hello"))

1
epascarello On

You said in the comments you want to chek to see how many checkboxes are checked. So add an event listener to the checkboxes (or use event delegation) and check to see how many are checked with a simple selector.

Basic concept:

const wrapper = document.querySelector("#wrapper");

const validateCheckboxes = function() {
  const checked = document.querySelectorAll(".chk:checked");
  const isValid = checked.length === 3;
  wrapper.classList.toggle("valid", isValid);
};

wrapper.addEventListener("change", validateCheckboxes);
.valid {
  background-color: green;
}
<div id="wrapper">
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
  <input type="checkbox" class="chk" />
</div>