简体   繁体   中英

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:

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

The actual DOM element is checked or unchecked correctly (which I can verify by posting the form). It is just the UI that is not being displayed correctly.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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