Home > Net >  If both checkboxes are true, then show DIV
If both checkboxes are true, then show DIV

Time:10-06

I am trying to show a Div that contains a button element, but only when BOTH checkboxes have been "agreed" to. I have tried to use JS to check this and then set the style display when each checkbox is clicked.

HTML:

<div class="agreement_box">
  <input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
  <input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>

<div id="submit_btn" class="profileSubmit_btn" style="display:none">
  <button>
  BUTTON
  </button>
</div>

JS:

function showMe(box) {
  var chbox1 = document.getElementByID("box1");
  var chbox2 = document.getElementByID("box2");
  var vis = "none";

  if (chbox1.checked && chbox2.checked) {
    vis = "block";
    break;
  }

  document.getElementById(box).style.display = vis;
}

Fiddle: https://jsfiddle.net/nhykqodp/2/

I'm kinda new to JS and my HTML knowledge is about 10 years out of date at this point. Any help would be appreciated.

Thanks.

CodePudding user response:

If I run your code, it shows:

Uncaught SyntaxError: Illegal break statement

Thats because a break can only be used inside a loop.


Furthermore, you have a typo, it should be getElementById instead off getElementByID

Note: The d shouldn't be capitalised


  • Remove the break
  • Fix the typo's:

function showMe(box) {
  var chbox1 = document.getElementById("box1");
  var chbox2 = document.getElementById("box2");
  var vis = "none";

  if (chbox1.checked && chbox2.checked) {
    vis = "block";
  }

  document.getElementById(box).style.display = vis;
}
<div class="agreement_box">
  <input type="checkbox" id="box1" onclick="showMe('submit_btn')">
</div>
<br>
<div class="agreement_box">
  <input type="checkbox" id="box2" onclick="showMe('submit_btn')">
</div>

<div id="submit_btn" class="profileSubmit_btn" style="display:none">
  <button>
  BUTTON
  </button>
</div>


Using an in-line if statement, we can remove the vis variable so we can alter the style right away like so:

function showMe(box) {
  const chbox1 = document.getElementById("box1");
  const chbox2 = document.getElementById("box2");
  document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}

CodePudding user response:

Little syntax error just replace document.getElementByID to document.getElementById

  • Related