【问题标题】:Asp.net MVC check/uncheck the checkbox based on a value?Asp.net MVC 根据值检查/取消选中复选框?
【发布时间】:2017-02-08 23:53:43
【问题描述】:

我正在研究 asp.net MVC 5,我在input 字段中添加了一个bootstrap toggle switch 类型为checkbox,如下所示

 <input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">

我想根据 OnOff 值检查/取消选中复选框

注意:默认情况下它始终开启

我想在我的 Javascript 中做这样的事情

If(command == "On")
{
  //then it will check the checkbox
}
else if (command =="Off")
{
  //then it will uncheck the checkbox     
}

我发现了许多与之相关的类似问题,我试图实现它但都是徒劳的

链接如下

  1. Link 1
  2. Link 2
  3. Link 3
  4. Link 4

我也尝试添加$('input:checkbox[name=cmdName]').attr('checked', false);,包括setAttributeremoveAttribute.prop 和许多其他人,但无法完成任务,我不知道是什么问题

我正在使用jquery 3.1.0,下面是我的参考资料

<head>
<title>@ViewBag.Title</title>
@*All the javascript and css files that are required by the
    application can be referenced here so that there is no
    need to refrence them in each and every view*@


<script type="text/javascript" src="~/Scripts/jquery-3.1.0.min.js"></script>
<script src="~/Scripts/bootstrap-toggle.js"></script>
<link href="~/Content/bootstrap-toggle.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?key=MyKey"></script>


<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="icon" href="favicon.ico" type="image/ico" />
<link rel="shortcut icon" href="~/favicon.ico" /></head>

任何帮助将不胜感激

【问题讨论】:

    标签: javascript jquery checkbox twitter-bootstrap-3 asp.net-mvc-5


    【解决方案1】:

    查看THIS fiddle

    我使用 jquery 3.1.0 和 Chrome 来测试它。

    $("#toggler").on("click", function() {
        var state = $('#myCheckbox').prop("checked");
        if (!state)
            $('#myCheckbox').prop("checked", true);
        else
            $('#myCheckbox').prop("checked", false);
    });
    

    【讨论】:

    • 我同时使用 jquery 3.1.0 和 chrome,也使用了 .prop 但没有用
    【解决方案2】:

    您检查控制台是否有任何错误?我会说你的脚本顺序是错误的。尝试在bootstrap.min.js 之后包含bootstrap-toggle.js 脚本。

    如果没有错误,请尝试像这样切换复选框:

    $('#test_id').bootstrapToggle('on')
    

    或者

    $('#test_id').bootstrapToggle('off')
    

    【讨论】:

    • 我添加了用于设置复选框状态的方法,试一试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多