mardi 31 octobre 2017

unexpected javascript behavior in input type checkbox

I have an element in my asp.net core 2.0/mvc6 project which is an input of type checkbox. I was just testing how to change the value of another hidden element while toggling this checkbox and couldn't get it working, so I used the simple jquery that is shown to see what the click results were.

Html

<div class="col-xs-7 col-sm-8">
     <label class="css-input switch switch-sm switch-success">
          <input type="checkbox" id="validation-terms" name="validation-terms"><span></span> I agree to all terms
     </label>
 </div>
 <div class="col-xs-5 col-sm-4">
     <div class="font-s13 text-right push-5-t">
         <a href="#" data-toggle="modal" data-target="#modal-terms">View Terms</a>
      </div>
</div>
@Html.HiddenFor(m =>m.Terms, new { id="register-terms" })

Javascript

$terms is the variable for the element

//toggle the slider when terms modal agree button clicked
        $terms.on('click', function () {

            if ($terms.is(':checked')) {
                //$terms.prop('checked', false);
                //$('#register-terms').val(false);
                alert("changing to blank");
            } else {
                //$terms.prop('checked', true);
                //$('#register-terms').val(true); 
                alert("changing to green");
            }

        });

The page loads with the slider unchecked (blank, greyed out, whatever you want to call it) which is normal behavior unless you add the checked attribute. Upon clicking the checkbox (it is a slider) you would expect the javascript to detect it is unchecked and show the changing to green message, the behavior is the opposite! The first time you click it, you get the changing to blank message, the slider goes green, when you click it again, now it is in checked state (supposedly), you get the changing to green message and it goes back to blank.

What am I missing here?




Aucun commentaire:

Enregistrer un commentaire