在mvc5的复选框上点击一个下拉可见

Make a dropdown visible on check box click in mvc5

本文关键字:一个 mvc5 复选框      更新时间:2023-09-26

我有一个复选框。在这个复选框的点击,我想使一个下拉可见。代码如下

<div>
        <input type="checkbox" name="SchoolAdmin" value="True" id="schooladmin">I would like to register as a school admin<br>
    </div>
    <div>
        @Html.DropDownList("school", new List<SelectListItem>
        {
            new SelectListItem{ Text="Please select", Value = "-1" },
            new SelectListItem{ Text="School1", Value = "1" },
            new SelectListItem{ Text="School2", Value = "0" }
        })
    </div>

,上面的脚本如下

<script type="text/javascript">
$(document).ready(function() {
    if ($('.schooladmin').is(":checked")) {
        //show the hidden div
        $('#school').show("fast");
    } else {
        //otherwise, hide it
        $('#school').hide("fast");
    }
    $('.schooladmin').click(function () {
        // If checked
        if ($('.schooladmin').is(":checked")) {
            //show the hidden div
            $('#school').show("fast");
        } else {
            //otherwise, hide it and reset value
            $('#school').hide("fast");
            $('#school').val('');
        }
    });
});

有谁能帮帮我吗?

.schooladmin是一个ID,您正在对其应用类选择器,尝试ID选择器#为相同的

所以写

if($('#schooladmin').is(":checked") // add #
不是

if ($('.schooladmin').is(":checked") // remove .
世界各地的


你的代码应该是这样的:
$('#schooladmin').click(function () {
    if (this.checked)
        $('#school').show("fast");
    else
        $('#school').hide("fast");      
});

首先是$('#schooladmin'),而不是$('.schooladmin') schooladmin id 不是

使用

$('#schooladmin').change(function () {
    if (this.checked) {
        //show the hidden div
        $('#school').show("fast");
    } else {
        //otherwise, hide it and reset value
        $('#school').hide("fast");
        $('#school').val('');
    }
});

演示小提琴

试试这个

$(document).ready(function() {
   $('#schooladmin').on("change", function(){
       if($(this).is(":checked")){
       }else{
       }
   }).trigger("change")
});