Forums

Checkbox to show/ hide multiple text fields

marcinwolejko 30 Sep, 2015
Hi there Bob,
I come back with another question to you.
I'm trying to use the JS function I've found in FAQ section to show/ hide text field based on checkbox clicked.
I managed esily to link one checkbox with one text field, however I cannot make it work with three text fields.

I used this piece of code:
var checkboxes;
window.addEvent('domready', function() {
  var i, checkbox, textfield, div, textbox;
  checkboxes = {};
  // link the checkboxes and textarea ids here
  checkboxes['checkbox1'] = 'textfield1';
  checkboxes['checkbox1'] = 'textfield2';
  checkboxes['checkbox1'] = 'textfield3';

  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;
  }
} 


Generally, I want one checkbox, let's say checkbox1 to hide/ show textfield1, textfield2, textfield3.
Is it doable? WIth the code (slightly altered) I can only hide/ show the last textfield😟

Please help🙂
marcinwolejko 30 Sep, 2015
Calculus00 it's exactly the FAQ I used🙂 However, I need some more profound aid in that matter.
GreyHead 30 Sep, 2015
Hi marcinwolejko,

These lines won't work as you are over-writing the previous entries.
  checkboxes['checkbox1'] = 'textfield1';
  checkboxes['checkbox1'] = 'textfield2';
  checkboxes['checkbox1'] = 'textfield3';
I think you can do this by setting each entry to be an array of textfield names
  checkboxes['checkbox1'] = ['textfield1', 'textfield2', 'textfield3'] ;
  checkboxes['checkbox2'] = ['textfielda', 'textfieldb', 'textfieldc'] ;
  checkboxes['checkbox3'] = ['textfieldx', 'textfieldy', 'textfieldz'] ;
Then you should be able to loop through the array of textfields hiding or showing each of them.

Bob

PS The simple solution is to install CFv5 and use the ability to show/hide a container.
marcinwolejko 30 Sep, 2015
Thanks Bob, I will give it a try.
As to CF5 I know it works there with no problems whatsoever, but for the time being I need to stick to CFv4😟
This topic is locked and no more replies can be posted.