简体   繁体   中英

select2 - submit form on select

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.

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

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

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

A simple vanilla solution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM