How to make a select list mandatory based on the result of a checkbox?

42 Views Asked by At

I have a view in my asp .net nopcommerce project.

<div class="form-group row">
    <div class="col-md-3">
        <nop-label asp-for="IsNewCustomerDiscount" />
    </div>
    <div class="col-md-9">
        <nop-editor asp-for="IsNewCustomerDiscount" />
        <span asp-validation-for="IsNewCustomerDiscount"></span>
    </div>
</div>
    
<nop-nested-setting asp-for="IsNewCustomerDiscount">
    <div class="form-group row" id="pnlBranchesList">
        <div class="col-md-3"> 
            <nop-label asp-for="BranchesList" />
        </div>
        <div class="col-md-9">
            <nop-select asp-for="BranchesList" asp-items="Model.BranchList" asp-multiple="true"/>
            <span asp-validation-for="BranchesList"></span>
        </div>
    </div>
</nop-nested-setting>

I want to make my BranchList mandatory only when the IsNewCustomerDiscount checkbox is checked. The following is the javascript

<script>
$(document).ready(function() {
    $("#@Html.IdFor(model => model.DiscountTypeId)").change(toggleDiscountType);
    $("#@Html.IdFor(model => model.UsePercentage)").click(toggleUsePercentage);
    $("#@Html.IdFor(model => model.IsNewCustomerDiscount)").click(toggleBranchList);
    $("#@Html.IdFor(model => model.RequiresCouponCode)").click(toggleRequiresCouponCode);
    $("#@Html.IdFor(model => model.DiscountLimitationId)").change(toggleLimitation);
    //$("#IsNewCustomerDiscount").change(function () {
    //    toggleBranchesListValidation();
    //});

    toggleDiscountType();
    toggleLimitation();
    toggleUsePercentage();
    toggleRequiresCouponCode();
    toggleBranchList();
    //toggleBranchesListValidation();
});
function toggleBranchList() {
    if ($('#@Html.IdFor(model => model.IsNewCustomerDiscount)').is(':checked')) {
        $('#pnlBranchesList').showElement();
    } else {
        $('#pnlBranchesList').hideElement();
    }
}
$(document).ready(function () {
    $("#IsNewCustomerDiscount").change(function () {
        consol.log("bla");
        toggleBranchesListValidation();
    });

    function toggleBranchesListValidation() {
        var isNewCustomerChecked = $("#IsNewCustomerDiscount").is(":checked");
        var branchesListSelect = $("#BranchesList");

        if (isNewCustomerChecked) {
            branchesListSelect.removeAttr("data-val-required");
        } else {
            branchesListSelect.attr("data-val-required", "The BranchesList field is required.");
        }
    }

    // Initial validation setup
    toggleBranchesListValidation();
});
</script>

This is not working and is thorwing the validation of "The branchs is missing" what am I doing wrong here

0

There are 0 best solutions below