3

that might be a simple question, but I am not yet so firm with JavaScript.

I want to have a search form with autocomplete using select2.

When the user selects a result in the select2 dropdown box, I want to submit the search form right away so that I do not need a button for the form.

I found the select2:select event handler - but I do not get it to work. Any help?

My select2 works fine and if I include a button, I can submit the form and receive the selected object id:

<form action="" method="get" id="project-search">
        <select class="form-control"
                data-autocomplete-light-function="select2"
                data-autocomplete-light-url="/output/project-autocomplete/"
                data-placeholder="Suche nach Projektnr. oder Projektleiter"
                id="id_projekt" name="projekt">
            <option value="" selected="selected">----------</option>
        </select>
</form>

That javascript snippet does not seem to work:

<script type="text/javascript">
    $(document).ready(function() {
    $eventSelect.on("select2:select", function() {
       console.log("select2:select");
       $(this).parents('form').submit();
    });
});
</script>

Edit: I get this error message in my chrome console:

Uncaught ReferenceError: $eventSelect is not defined

Thank you!

I am using django with django-autocomplete-light for the backend btw.

teconomix
  • 227
  • 1
  • 3
  • 14

2 Answers2

3

https://api.jquery.com/change/

Jquery has a function able to detect changes on select/checkboxes. Try:

$('#id_projekt').change(function(){ $('#project-search').submit(); });

Berry M.
  • 469
  • 1
  • 4
  • 17
  • Great! That seems to work, thank you! I am just currious and would like to understand it better - why don't you use the "select2:select" event? Or why is that not even necessary? – teconomix Sep 22 '16 at 09:06
  • The select event does something completely different. Here's a good example: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onselect_html Also, in case you hadn't figured it out, `$().change()` does the same as `$().on('change')`. – Berry M. Sep 22 '16 at 14:31
0

A simple vanilla solution

<select onchange="this.form.submit()">
  ...
</select>