freckles.karin freckles.karin - 3 months ago 10
HTML Question

checkbox validation if the checkbox is displayed only

I have a form with a checkbox which is displayed in certain cases. I would like to check that the checkbox is checked only in case it's displayed, for other cases I would like the form to be submitted on click on the submit button. I wrote the following function, but it doesn't work:

function checkTheBox() {
window.onload = function() {
var visible = document.getElementById("checkbox").isDisplayed();
if(!visible)
return true;
else if(visible){
var checkbox = document.getElementById("checkbox");
if(checkbox.checked)
return true; }
else{
alert('You must agree to the terms first.');
return false;
}
}; }


These are my html elements:

<div class='input-block' id='div_checkbox' style='display: none;'>
<input type="checkbox" id="checkbox" name="checkbox" value="0">
<b>I agree to all terms and conditions</b><br />
</div>






What am I doing wrong?

Answer

You have to check, if that element is undefined:

But be careful, user can remove your checkbox via console, and will be able to submit your form without checking the checkbox.

Also you don't have to use window.onload = function() { ... }, simply use this code and call function checkTheBox on form submit:

function checkTheBox() {
  if (document.getElementById("checkbox") === 'undefined') {
    return true;
  }
  else {
    var checkbox = document.getElementById("checkbox");

    if (checkbox.checked) {
      return true;
    }
    else {
      alert('You must agree to the terms first.');
      return false;
    }
  }
}

But as @ADyson said, always validate your data on server side.