通过复选框隐藏/显示文本区域,这些复选框具有不同部分的相同类

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

本文关键字:复选框 同部 同类 隐藏 显示 文本 区域      更新时间:2023-09-26

嗯,我有一个感兴趣的表格,当我从选择列表中选择一个选项(例如汽车、电机)时,它会给我与选项相关的内容。

这是测试页面->这里是

我还为每个部分创建了复选框(来自上面的实例),我希望在选中特定复选框(.other)时显示详细信息的文本框(.textbox),在取消选中时默认隐藏。我为这个特定的复选框和每个文本区域的每个部分指定了相同的类。对于复选框->.other和文本区域->.textbox

这是每个部分的代码(复选框):

汽车

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

电机

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

我尝试了这个JS代码:

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

但我做错了什么。你有什么建议?提前谢谢。

检查演示[点击此处]

在选择复选框和类其他时,您希望显示相应的文本区域

您可以使用以下代码片段进行解析。

$(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();
        });
    });

用作

<script>
    $(function(){   
        $(".other").click(function(){
            if((this).is(":checked")==true)
            {
                $(".textbox").show();
            }
            else
               $(".textbox").hide();
        });
    })
</script>

我对您的代码进行了一些调整

jQuery代码:

  $('.other').removeAttr('checked');
  $('.other').on('click', function () {
    $(this).closest("div.par").find('.textbox').toggle();
  });

JSFIDDLE:

http://jsfiddle.net/dreamweiver/1y47bxfh/4/

注意:当你在代码中使用jquerylib时,一定要使用它,不要使用原始的js代码。正如标语本身所暗示的write less do more

快乐编码:)