0

I am trying to make sure that at least one 'input checkbox is checked in this list there is about 10 items but I am not sure how to do this? Do I need a flag in the model?

 <div>* Data</div>
 @Html.ValidationMessageFor(x => x.flgData,"", new { @class = "text-danger" })
    <ul>
     @foreach (var item in Model.ListOfData)
     {
          <li>
               <input type="checkbox" value="@item.Value" name="chk" />
               <label asp-for="@item.Selected">@Html.Raw(@item.Name)</label>
               <input type="hidden" asp-for="@item.DictionaryId" />
               <input type="hidden" asp-for="@item.Name" />
          </li>
     }
    </ul>
1
  • If you are doing pre-submission validation, you would collect all of these options with javascript then count the checked items. Commented Jan 14, 2021 at 18:32

1 Answer 1

1

You could loop though all the checkbox and check if it is checked

HTML

<input type="button" id="btnSubmitCB" value="Submit" class="btn btn-primary" />
<input type="checkbox" class="chkbox" value="Bike" /> Bike
<input type="checkbox" class="chkbox" value="Car" /> Car
<input type="checkbox" class="chkbox" value="Boat" /> Boat

JQuery

$(document).ready(function () { 

    $('#btnSubmitCB').click(function () {
        var cbChecked = false;
        $('input[type=checkbox]').each(function () {
            if (this.checked) {
                cbChecked = true;
                return false;
            }
        });

        if (cbChecked) {
            alert("At least one checkbox is checked");
        }
        else {
            alert("No checkbox is checked");
        }

    });

});

Another way without using .each function

$(document).ready(function () { 
    $('#btnSubmitCB').bind("click", function () {
        let checkedCount = $('input[type=checkbox]:checked').length;
        if (checkedCount == 0) {
            alert("no checkbox has been checked")
        }
        else {
            alert("checkbox has been checked");
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.