Hide/Display a input field based on value from Htm

2019-08-26 04:10发布

问题:

I have a scenario where I have two different div's and the later should disappear based on boolean value from earlier div. if the radiobutton value is true, later div should be a required filed.

Actual Code:

<div class= row ">
<div class="row col-lg-offset-2 top-buffer">
    <h4><strong><span>Is Employment Offered?</span> <span class="text-danger">*</span></strong></h4>
        @Html.RadioButtonFor(model => model.IsOffered, true) @Html.Label("Yes")
        @Html.RadioButtonFor(model => model.IsOffered, false) @Html.Label("No")
        <br>
</div>
<div class="row col-lg-offset-2 top-buffer" id="employeeNumber">
    <div class="col-sm-2"><b>Enter Employee Number</b></div>
        <div class="col-sm-10">
                @Html.TextBoxFor(model => model.EmployeeNumber, new { @class = "form-control" })
            <br />
        </div>
    </div>
</div>

<script>
$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function() {
    if ($(this).val() == "true") {
        $("#employeeNumber").show();
    }
});

I tried above, but no luck. Thanks you for your time!

回答1:

Change it to "True":

$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function () {
    if ($(this).val() === "True") {
        $("#employeeNumber").show();
    } else {
        $("#employeeNumber").hide();
    }
});

Because Boolean.ToString() returs "True" instead of "true". So this value is added to the radio that is generated by razor.

Why?