auto submit, once option selected

Viewed 143

having some trouble with the code below.

What this code does

I have many list items (below is an extract of just one) items made out of selects and options and a sole input with the type="submit"

once an option is selected the user can click the input which acts as a filter button and submit the form, the user then will get back a directory of that search.

What I'm trying to achieve

I want the input to submit soon as the user selects an option. It needs to feel like it auto-loaded once selected then the user may select another option to add on top of that option and then the process repeats.

I've been trying to make this work with the code below but no luck.

--note--

  1. I don't want the form to submit if the option is disabled and showing what would be the placeholder.

  2. if there's a clean JavaScript way that can be a solution as well.

jQuery(document).ready(function($){
  $("select").change(function () {
    $("select").data("changed",true);
  });
  if ($("select").data("changed")) {
    $("#search").click();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>

<strong>Gender:</strong><br>

<select id="gender" name="gender">

<option name="gender[]" value="0"> </option>
<option value="" disabled="" selected="" hidden="">Select Gender</option>
<option name="gender[]" value="female"> Female</option>
<option name="gender[]" value="male"> Male</option>
<option name="gender[]" value="trans"> Trans</option>

</select>                       
</li>


<input id="search" name="theForm" class="filterBtn" type="submit" value="Filter">

1 Answers

All you need to do is to move the statement inside the if to the callback function of the select event handler.

Also if you are having more than one select, be sure to clear the data changed to false just above/below the line $(this).data('changed', true); if you are going to use it elsewhere.

The issue in what you have done is, that the if condition wont get executedr when a selection is made. It gets exectuted only once when the page loads.

jQuery(document).ready(function($){
  $("#gender").change(function () {
    $(this).data("changed",true);
    $("#search").click();
  });
  $('#search-form').on('submit', function (ev) {
    ev.preventDefault();
    alert('searching');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>

<strong>Gender:</strong><br>

<select id="gender" name="gender">

<option name="gender[]" value="0"> </option>
<option value="" disabled="" selected="" hidden="">Select Gender</option>
<option name="gender[]" value="female"> Female</option>
<option name="gender[]" value="male"> Male</option>
<option name="gender[]" value="trans"> Trans</option>

</select>                       
</li>

<form id="search-form">
<input id="search" name="theForm" class="filterBtn" type="submit" value="Filter">
</form>

Related