jquery - javascript how to see the razor variable? and set checkbox? -
have edit form has checkboxes. if checkbox checked uses script send yes/no value onto hiddenfor( variable.
<div class="form-group"> @html.labelfor(model => model.ptmodel1, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div class="checkbox"> @html.checkbox("checkbox") @html.hiddenfor(model => model.ptmodel1, new { htmlattributes = new { @class = "form-control" } }) </div> </div>
script code:
$("#checkbox1").on("click", function () { var mycheckbox1 = $("#checkbox1"); if (mycheckbox1.is(":checked")) { $("#ptmodel1").val("yes"); } else { $("#ptmodel1").val("no"); } });
ok on create , edit methods in mvc bootstrap forms works fine along script add yes/no; problem happens when going edit, if value checked , set yes, defaults no, , checkbox not checked. how make checkbox checked if value thats in form ptmodel1 variable "yes" ??
<script> $(window).load(function () { switch (("#ptmodel1").val) { case "yes": $("#checkbox1").checked; alert("in switch case"); break; default: alert("in switch case default" + "#ptmodel1"); } }); </script>
question: how set checkbox, if value of variable "yes" ? syntax isnt doing expect.
2nd question: @ 1 time had saving tiny icon image of checked checkbox, in index view display icon. whatever makes save , display state. checkbox must reflect checkedness of checkbox
see mistakes highlighted in below code:
$(window).load(function () { switch ($("#ptmodel1").val()) { // ^ ^^ case "yes": $("#checkbox1").prop('checked', true); // ^^^^^^^^^^^^^^^^^^^^^ alert("in switch case"); break; default: alert("in switch case default" + "#ptmodel1"); } });
or
shorter version:
$(window).load(function () { $('#checkbox1').prop('checked', $('#ptmodel1').val() == 'yes'); });
shorter version of event handler
$("#checkbox1").on("click", function () { $('#ptmodel1').val($(this).is(':checked') ? 'yes' : 'no'); });
Comments
Post a Comment