简体   繁体   English

根据HTML 5复选框输入显示项目

[英]Displaying Items Based On HTML 5 Checkbox Input

If I have two HTML 5 checkboxes like these... 如果我有两个这样的HTML 5复选框...

<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? 如何根据用户输入显示文本区域(或任何其他HTML 5项目)? For example, if they selected value1 show one block of text, if they selected value2 show a different block of text. 例如,如果他们选择value1显示一个文本块,则如果他们选择value2显示另一个文本块。 What would be the best way to do this, without having to reload the page or submit a form? 无需重新加载页面或提交表单的最佳方法是什么?

Thanks. 谢谢。

If the elements are siblings, the simplest approach would be to use the :checked pseudo class to determine if the checkbox is checked. 如果元素是兄弟姐妹,则最简单的方法是使用: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. 如果要执行JavaScript路由,则需要将change事件侦听器附加到checkbox元素。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM