Wizard-of-Koz
Wizard-of-Koz

Reputation: 1787

NET Core - Submit on input change, not button click

Currently, I have a form that calls a method in my controller. It sends a string as a parameter to my IActionResult (the string is always a numer since I am getting it from an input of type range between 1 and 12). The method looks like this: public IActionResult ChangeForecastMonths(string forecastMonths) The code in my view is the following:

<form asp-action="ChangeForecastMonths">
    <input asp-for="FutureForecastMonths" name="forecastMonths" type="range" class="custom-range" min="1" max="12" step="1" />
    <input type="submit" value="Save" class="btn btn-primary" />
</form>

What I'm trying to do is -- instead of the ChangeForecastMonths method being called whenever the submit button is clicked -- to actually have it called whenever the input field changes its value.

Upvotes: 1

Views: 3235

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12705

You could hook to the change() event of the input, then fire a submit() on the parent form, like this:

<form asp-action="ChangeForecastMonths">
  <input asp-for="FutureForecastMonths" name="forecastMonths" type="range" class="custom-range" min="1" max="12" step="1" />
  <input type="submit" value="Save" class="btn btn-primary" />
</form>

@section Scripts
{
  <script>
    $('form input').change(function() {
        $(this).closest('form').submit();
    });
  </script>
}

Result: enter image description here

Upvotes: 3

Related Questions