select2 - submit form on select

teconomix picture teconomix · Sep 21, 2016 · Viewed 7.5k times · Source

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.

Answer

Berry M. picture Berry M. · Sep 21, 2016

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

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

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