i'm implementing a checkbox question for let user to choose. However, if admin set the question mandatory to true, the checkbox must select at least 1 to submit, else a message will prompt user to select. Tried the jquery but when click button, nothing happen.
Any mistakes that ive done?
My View:
@model List<IFXSurveyTool.Models.AnswerQuestionViewModel>
<script>
var messageContainer = $('.errormessage');
$('#save').click(function () {
// Get all mandatory containers
var mandatory = $('.mandatory');
$.each(mandatory, function () {
var numChecked = $(this).find('input:checked').length;
if (numChecked === 0) {
messageContainer.text('At least one checkbox must be selected.');
return false;
}
});
});
$('.mandatory').on('click', 'input[type="checkbox"]', function () {
messageContainer.text('');
});
</script>
<br />
<h2>Questions</h2>
<br />
@using (Html.BeginForm())
{
<div class="errormessage"></div>
<div class="checkboxcontainer mandatory">
@for (int x = 0; x < Model[i].Choice_SubQuestion.Count(); x++)
{
<input type="checkbox" name="[@i].MultiAnswer[@x]" value="@Model[i].Choice_SubQuestion[x]" />
@Html.HiddenFor(m => m[i].MultiAnswer[x])
@Html.LabelFor(m => m[i].MultiAnswer[x], Model[i].Choice_SubQuestion[x].ToString(), new { @class = "questionlist1" })
}
</div>
<button type="button" id="save">Save</button>
}
After generating the checkbox in HTML:
<div class="checkboxcontainer mandatory">
<input type="checkbox" name="[0].MultiAnswer[0]" value="1">
<input name="[0].MultiAnswer[0]" type="hidden" value="">
<label class="questionlist1" for="">1</label>
<input type="checkbox" name="[0].MultiAnswer[1]" value="2">
<input name="[0].MultiAnswer[1]" type="hidden" value="">
<label class="questionlist1" for="">2</label>
<input type="checkbox" name="[0].MultiAnswer[2]" value="3">
<input name="[0].MultiAnswer[2]" type="hidden" value="">
<label class="questionlist1" for="">3</label>
</div>
valueattribute of the checkbox@Model[i].Choice_SubQuestion[x]which assuming its not abooland@Model[i].MultiAnswer[x]is, binding would also fail. You need to show your models and the outerforloop in the view to understand better what your trying to do.if (Model[i].Mandatory == true), give the div a class name (say)<div class="mandatory">. Then you can handle the.submit()event, get all elements with that class name, and use a$.each()function to test of any of its checkboxes are checked. If not, then cancel the submit and display an error.