简体   繁体   中英

javascript how to see the razor variable? and set checkbox?

have an edit form that has checkboxes. if the checkbox is checked it uses script to send a yes/no value onto a 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 the Create and Edit methods in the mvc bootstrap forms it works fine along with some script to add the yes/no; but the problem happens when going to do an Edit, if the value IS checked and IS already set to Yes, it always defaults to no, and the checkbox is not checked. how to make a checkbox checked if the value thats now in the form PTModel1 variable is "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 to set the checkbox, if the value of the variable is "yes" ? the syntax isnt doing what i expect.

2nd question: at one time i had this saving a tiny icon image of a checked checkbox, so in the index view it would display the icon. whatever makes it save and display the state. the checkbox must reflect the checkedness of the checkbox

See the 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');
});

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