Enable submit button when select checkbox

I have try a few examples of enable the submit button when checkbox is selected but i’m getting nowhere. Below is one of my attempts, where the submit button is disabled until the checkbox is selected. Please let me know what am i missing.

function checked(sub1) {
  var myLayer = document.getElementById(sub1);
  var input = myLayer.childNodes[0];
  if (input.checked == true) {
    myLayer.disabled = "";
  } else {
    myLayer.disabled = "disabled";
  }
}
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
  <input type="checkbox" id="termsChkbx " onchange="checked('sub1')" />
</p>
<p>
  <input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled" />
</p>

solution

Nobody has explained why your code isn’t working.

For one, you aren’t selecting the input checkbox element properly. It is not a child node of the button element. You could either get a reference to the checkbox by passing this in the onchange event, or you could pass the event object and access the checkbox element through the event.target property:

For example:

<input type="checkbox" id="termsChkbx " onchange="isChecked(this, 'sub1')" />

Then you can access a reference to the checkbox element that fired on the change event:

function isChecked(checkbox, sub1) {
  // checkbox
}

After changing a couple things, it would work as expected:

function isChecked(checkbox, sub1) {
  var button = document.getElementById(sub1);


  if (checkbox.checked === true) {
    button.disabled = "";
  } else {
    button.disabled = "disabled";
  }
}

However, you can simplify the code and rewrite it to:

Example Here

<input type="checkbox" id="termsChkbx " onchange="isChecked(this, 'sub1')" />
function isChecked(checkbox, sub1) {
  document.getElementById(sub1).disabled = !checkbox.checked;
}

As a side note, I would highly suggest using unobtrusive JavaScript and add an event listener to the element in order to avoid inline onchange events:

Example Here

document.getElementById('termsChkbx').addEventListener('click', function (e) {
  document.getElementById('sub1').disabled = !e.target.checked;
});