Search code examples
javascriptcheckboxinfo

Reveal additional info based on two (out of three) checkboxes JavaScript


I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.

Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.

<script>
 
var checkboxes;
window.addEvent('domready', function() {
  var i, checkbox, textarea, div, textbox;
  checkboxes = {};
 // link the checkboxes and textarea ids here
  checkboxes['checkbox_1'] = 'textarea_1';
  checkboxes['checkbox_2'] = 'textarea_2';
  checkboxes['checkbox_3'] = 'textarea_3';
 
  for ( i in checkboxes ) {
    checkbox = $(i);
    textbox = $(checkboxes[i]);
    div = $(textbox.id + '_container_div');
    div.dissolve();
    showHide(i);
    addEventToCheckbox(checkbox);
  }
 
  function addEventToCheckbox(checkbox) {
    checkbox.addEvent('click', function(event) {
      showHide(event.target.id);
    });
  }
});
 
function showHide(id) {
  var checkbox, textarea, div;
  if(typeof id == 'undefined') {
    return;
  }
  checkbox = $(id);
  textarea = checkboxes[id];
  div = $(textarea + '_container_div');
  textarea = $(textarea);
  if(checkbox.checked) {
    div.setStyle('display', 'block');
    //div.reveal();
    div.setStyle('display', 'block');
    textarea.disabled = false;
  } else {
    div.setStyle('display', 'none');
    //div.dissolve();
    textarea.value = '';
    textarea.disabled = true;
  }
}
 
 
      <label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
 
 
return c <= 1;
};
 
</script>
 
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
 
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
 
</form>
 
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
 
pieces of info:</h2></p>
</style>


Solution

  • Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.

    I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');