1

The purpose is to check whether the two fields (username and password) have text entered, if so, check the checkbox, if not, uncheck the checkbox.

It works if I enter text in both. It unchecks if I delete the text in the user field; however, if I reenter a character in the user field, the box will not recheck. What could be happening?

<div class="controls"> 
    @Html.CheckBoxFor(model => model.checkboxId, new Dictionary<string, object> { { "disabled", "disabled" } })
</div>

<script type="text/javascript">
 $(document).ready(function() {
    $('#Username, #Password').change(function () {
        var username = $('input#Username').val();
        var password = $('input#Password').val();
        if (username.length != 0 && password.length != 0) {
            $('#checkboxId').attr('checked', true);
        }
        else {
            $('#checkboxId').removeAttr('checked');
        }
    });
</script>
scaborski
  • 145
  • 16
  • that was my mistake here, the code has that '#' in there, edited the question – scaborski Jul 22 '15 at 21:04
  • possible duplicate of [Checking a checkbox with jQuery?](http://stackoverflow.com/questions/426258/checking-a-checkbox-with-jquery) – Charlie Jul 22 '15 at 21:11

2 Answers2

2

To check and uncheck a checkbox input using jQuery, use $().prop("checked",true) and $().prop("checked",false). Simply removing the checked attribute does not uncheck the checkbox, but the prop() function does.

devinallenaz
  • 430
  • 3
  • 9
0

You are removing the attribute so it can no longer be set to true.

Instead you should use prop()...

$('#Username, #Password').change(function () {
        var username = $('input#Username').val();
        var password = $('input#Password').val();
        if (username.length != 0 && password.length != 0) {
            $('#checkboxId').prop('checked', true);
        }
        else {
            $('#checkboxId').prop('checked',false);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="Username" placeholder="Username">
<input type="text" id="Password" placeholder="Password">
<input type="checkbox" id="checkboxId">
Turnip
  • 35,836
  • 15
  • 89
  • 111