According to your description, the following code can be achieved. When the checkbox is not selected or No is selected, the hidden field value is False. When "Yes" is selected for this checkbox, the hidden field value is "True".
@model MvcDemo.Models.HealthStatusData
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
<td style="width: 50%; font-weight: bold; padding-top: 10px;">
@Html.Label("HealthStatus?", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<input type="checkbox" id="HealthStatusTrue" name="HealthStatus" value="true" class="healthstatus-checkbox" @(Model.HealthStatus == true ? "checked" : "") />
Yes
<input type="checkbox" id="HealthStatusFalse" name="HealthStatus" value="false" class="healthstatus-checkbox" @(Model.HealthStatus == false ? "checked" : "") />
No
</div>
<input type="hidden" name="HealthStatus" id="myHiddenInput" value="false" />
</td>
<a id="approveControlsId" onclick="approve();" class="btn btn-primary" style="min-width: 100px;margin-top:5px;"><i class="glyphicon glyphicon-ok"></i> agree </a>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$('.healthstatus-checkbox').on('change', function () {
if ($("input[name='HealthStatus']:checked").val() == 'true') {
$('#myHiddenInput').val("True");
}
else {
$('#myHiddenInput').val("False");
}
});
function approve() {
var hiddenvalue = $('#myHiddenInput').val();
alert(hiddenvalue);
}
</script>
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.