javascriptjquerycheckbox

hide/show textarea via checkboxes with same classes for different sections


Well, I have a form of interest and when I select an option from select list (e.g cars, motors) it gives me content relating to option.

Here is the test page -> Here

I also have created checkboxes for each section (from above instance) and I want when I check a specific checkbox (.other) to display a text box for details (.textbox) and when I uncheck it to get hidden by default. I gave to this specific checkbox and each textarea the same class for each section. For checkbox -> .other and for textarea -> .textbox

This is the code (of checkboxes) for each section:

Cars

<ul style="list-style-type: none;">
   <li><label for="thrausi"><input type="checkbox" name="thrausi" id="thrausi">text</label></li>
   <li><label for="odiki-car"><input type="checkbox" name="odiki-car" id="odiki-car"text</label></li>
   <li><label for="nomiki"><input type="checkbox" name="nomiki" id="nomiki">text</label></li>
   <li><label for="other-car"><input type="checkbox" class="other">**Other details**</label></li>
</ul>
<textarea class="textbox" name="other" style="display:none; width: 255px;" placeholder="text"></textarea>

Motors

<ul style="list-style-type: none;">
   <li><label for="odiki-moto"><input type="checkbox" name="odiki-moto" id="odiki-moto">text</label></li>
   <li><label for="other"><input type="checkbox" class="other">**Other details**</label></li>
  </ul>
<textarea class="textbox" name="other" style="display:none; width: 255px;" placeholder="text"></textarea>

And I tried this JS code:

<script type="text/javascript">
window.onload=function(){
var elem = document.getElementByClassName('textbox'),
    checkBox = document.getElementByClassName('other');
checkBox.checked = false;
checkBox.onchange = function() {
    elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
}
</script>

But I do something wrong. What do you suggest? Thanks in advance.


Solution

  • Check the DEMO [Click Here]

    As on the selection of check box with class other you want to show the corresponding textarea

    you can use the following code snippet for the resolution.

    $(document).ready(function () {
            $(".other").change(function () {
                if ($(this).is(":checked"))
                    $(this).parent().parent().parent().next(".textbox").show();
                else
                    $(this).parent().parent().parent().next(".textbox").hide();
            });
        });