0

I have a filter that filters my products by manufacturer. The problem is that I want for the products to show when I click the checkbox, without having to click the Save button.

@model FilterViewModel
@{
    var formController = "";
    var formAction = "";

    if (Model.FilterType == "name")
    {
        formController = "Home";
        formAction = "ProductSearch";
    }
    if (Model.FilterType == "manufacturer")
    {
        formController = "Manufacturer";
        formAction = "ManufacturerInfo";
    }
    if (Model.FilterType == "category")
    {
        formController = "Home";
        formAction = "ProductCategory";
    }
}

<h5>Filter</h5>
<br />
<form id="filterForm" asp-area="" asp-controller="@formController" asp-action="@formAction" method="get">
    @if (Model.ManufacturerFilterViewModel.Count > 0)
    {
        <h6>Producător</h6> <!-- category filter -->
        <hr />
        @foreach (var manufacturer in Model.ManufacturerFilterViewModel)
        {
            string labelVaue = $"{manufacturer.Name} ({manufacturer.Quantity})";

            <div>
                <input type="checkbox" id="@manufacturer.Name" name="Manufacturer" value="@manufacturer.Name" />
                <label for="@manufacturer.Name">@labelVaue</label>
            </div>
        }
        <button type="submit" class="btn btn-sm btn-primary">Save</button>

        <br /><br />
    }
peterh
  • 11,875
  • 18
  • 85
  • 108
shade1337
  • 83
  • 1
  • 2
  • 9

1 Answers1

2

You can submit the form when clicking on a checkbox using JavaScript. An example for your form would be:

<script type="text/javascript">
var form = document.getElementById("filterForm"); // get the form
var inputs = document.getElementsByName("Manufacturer"); // get the checkboxes
inputs.forEach(function(input) { // iterate through the checkboxes ...
    input.addEventListener("click", function () { // ... and register a listener on click ...
        form.submit(); // ... that submits the form
    });
});
</script>

But you might want to use jQuery. Also see this question for further information.

user7217806
  • 2,014
  • 2
  • 10
  • 12
  • Thank you, it worked. But what if i have multiple category filters? – shade1337 Sep 01 '19 at 09:07
  • There are several options to do that, one way would be passing the checkbox values to the controller, see this [tutorial](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/controller-methods-views?view=aspnetcore-2.2). – user7217806 Sep 01 '19 at 10:50