Displaying Items Based On HTML 5 Checkbox Input

If I have two HTML 5 checkboxes like theseā€¦

<input name="your_name" value="your_value1" type="checkbox">
<input name="your_name2" value="your_value2" type="checkbox">

How can I display a textarea (or any other HTML 5 item) based on the input of the user? For example, if they selected value1 show one block of text, if they selected value2 show a different block of text. What would be the best way to do this, without having to reload the page or submit a form?


solution

If the elements are siblings, the simplest approach would be to use the :checked pseudo class to determine if the checkbox is checked. Then you can use the general sibling selector, ~, to select the following sibling element(s) depending on the checked state:

[name="your_name"]:checked ~ .block1 { display: block; }
[name="your_name2"]:checked ~ .block2 { display: block; }
p { display: none; }
<input name="your_name" value="your_value1" type="checkbox">
<input name="your_name2" value="your_value2" type="checkbox">
<p class="block1">Block 1</p>
<p class="block2">Block 2</p>

If you want to go the JavaScript route, you would need to attach a change event listener to the checkbox element.

For instance:

var checkbox = document.querySelector('[name="your_name"]'),
text = document.querySelector('.text');
checkbox.addEventListener('click', function (e) {
  text.style.display = e.target.checked ? 'block' : 'none';
});
<input name="your_name" value="your_value1" type="checkbox">
<p class="text" style="display: none">Block 1</p>