选中单选框后显示复选框和文本字段的列表

Displaying a list of checkboxes and text field after radio is checked

本文关键字:文本 字段 列表 复选框 单选框 显示      更新时间:2023-09-26

我有一个包含以下字段的表单:

<div>
     <input name="department" type="radio" value="1" required >
     <label for="Orchestra">Orchestra</label>
</div>
<div>
      <input name="department" type="radio" value="2">
     <label for="Band">Band</label>
</div>

我想做的是,只有在选中了"波段"的单选按钮时,才能显示不同的复选框和注释文本字段。如果未选中此项,则复选框应消失。我在网上找到了几个例子,但由于某种原因,我无法让它们发挥作用。问题一定是我不知道Javascript或JQuery:(如有帮助,不胜感激。

我尝试过在stackOverflow和其他网站上看到的不同东西,但我对Javascript一无所知,无法让它发挥作用。

我创建了一个带评论的fiddle来帮助你完成你的要求,同时也为你提供实际发生的事情的线索。我建议你利用在线可用的许多资源深入研究JavaScript/JQuery,但目前,我希望我的评论能帮助你开始。

这里的主要收获是,我们使用JavaScript来"监听"有问题的输入是否被选中,而不是被选中——基于这个值,我们可以决定我们的视图会是什么样子——在这种情况下,隐藏或显示元素。

JS

$(function () {
    // Create selectors for relevant DOM elements
    var $Department = $('input[name="department"]');
    var $BandSelected = $('#BandSelected');
    // Create a function that you pass 
    // the value of the input element in question.
    // Return TRUE/FALSE based on equality to 2, 
    // the `value` associated with the 'Band' input 
    function isBandsSelected(val) {
        return val == 2;
    }
    // Attach an event listener on `click' of inputs
    $Department.click(function () {
        // Assign a variable to the function that determines if the input
        // we click on is 'Band' (has a value of 2)
        var showBand = isBandsSelected($(this).val());
        // If `showBand` returns TRUE, show our `BandSelected` div
        if (showBand) {
            $BandSelected.show();
            // If `showBand` returns FALSE, show our `BandSelected` div
        } else {
            $BandSelected.hide();
        }
    });
});

标记

<div>
    <input name="department" type="radio" value="1" required>
    <label for="Orchestra">Orchestra</label>
</div>
<div>
    <input name="department" type="radio" value="2">
    <label for="Band">Band</label>
</div>
<div id="BandSelected" class="hidden">
    Band is selected
</div>

演示Fiddle:http://jsfiddle.net/4x1ybqyv/