简体   繁体   English

更改复选框时需要更新UI

[英]Need to update UI when a checkbox is changed

I have a situation where is have a Bootstrap 3 based page which has a checkbox on it: 我有一个基于Bootstrap 3的页面,上面有一个复选框:

<input type="checkbox" value="Y" id=userActive checked>

Before I display the form I want to set the correct state based on the value of the field in the database like so: 在显示表单之前,我想根据数据库中字段的值设置正确的状态,如下所示:

if (ra.active=='Y') {                
        $("#userActive").prop("checked",true);                
} else {                
        $("#userActive").prop("checked",false);                
} 

The problem is that the UI display of the form is always Checked (as if true). 问题在于该窗体的UI显示始终处于选中状态(就像是true)。 Actually it is always the value of the initial state. 实际上,它始终是初始状态的值。 If I remove the CHECKED parameter from the HTML then the checkbox UI display will represent UNCHECK regardless of the value. 如果我从HTML中删除CHECKED参数,则复选框UI显示将代表UNCHECK,而不管该值如何。

The actual DOM element is checked or unchecked correctly (which I can verify by posting the form). 实际的DOM元素是否已正确选中或未选中(我可以通过发布表单进行验证)。 It is just the UI that is not being displayed correctly. 只是UI无法正确显示。

There is nothing wrong with your code, here it is working exactly as you describe. 您的代码没有错,这里的代码完全按照您的描述工作。 Perhaps you have some other code interfering or some special CSS styling on your checkboxes? 也许您的复选框有一些其他代码干扰或某些特殊的CSS样式?

 //Some setup to mimic your code var ra = { active: 'N' }; if (ra.active == 'Y') { $("#userActive").prop("checked", true); } else { $("#userActive").prop("checked", false); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <div class="container"> <div class="row"> <div class="col-xs-12"> <input type="checkbox" value="Y" id=userActive checked> </div> </div> </div> 

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

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