Reputation: 891
My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
@Html.LabelFor(model => model.BoolField1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { @class = "form-control", @id = "bool1" } })
@Html.ValidationMessageFor(model => model.BoolField1, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BoolField2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { @class = "form-control", @id = "bool2" } })
@Html.ValidationMessageFor(model => model.BoolField2, "", new { @class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
Upvotes: 0
Views: 1670
Reputation: 1294
First you need to correct syntax for EditorFor () it should be like following
@Html.EditorFor(model => model.BoolField1, new { @class = "form-control", @id = "bool1" })
instead of
@Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { @class = "form-control", @id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});
Upvotes: 1