0

I have a modal with a select. The modal is loaded with ajax. I want the select on it to use chosen, so in my success event I have this:

$.ajax({
    url: $params.testPlanImportPath,
    method: 'POST'
}).success(function (response) {
    $modal.html(response).modal('show')
    $modal.find('#test_plan_form_project').chosen({
        width: '100%'
    });
});

That part works well so far, the only issue is that I want my select to close when I click on an item. I believe that it is supposed to be the default behavior but for some reason it doesn't work for me. I have other chosen in my website, and no issue with them.

I tried adding an event to close it manually when it is selected but it didn't do anything:

$modal.find('#test_plan_form_project').chosen({width:'100%'}).on('change', function(){
     //the code here was executed but it didn't close anyway
     console.log('close');
     $modal.find('#test_plan_form_project').trigger("chosen:close")
});

I also tried adding the options that I have in my other chosens, no effect.

$modal.find('#test_plan_form_project').chosen({
    width: '100%',
    allow_single_deselect: true,
    search_contains: true,
    disable_search_threshold: 10
});

There is no errors in the console at any point and my console.log() in the event shows correctly. If I remove the chosen, the select works as expected but I really would like to have the chosen interface.

I feel like I might be missing something obvious.

The html of the select (with twig)

<div class="row">
    <div class="col-sm-12 p-0">
        <label class="control-label required" for="test_plan_form_project">Projet</label>
        <select class="form-control" name="test_plan_form_project" id="test_plan_form_project">
            {% for project in projects %}
                <option value="{{project.id}}">{{project.name}}</option>
            {% endfor %}
        </select>
    </div>
</div>

I know there is a very similar question: JQuery chosen not closing on select

I have look at this question but the only answer didn't help and the issue in that case turned out to a be a missing .css, which is not the issue for me.

Liora Haydont
  • 1,252
  • 1
  • 12
  • 25

1 Answers1

1

You can remove the Chosen-Drop manually by removing the chosen-container-active and the chosen-with-drop class auto-generated by chosen when you open a dropdown :

var chosenContainer = $('.chosen-container');
chosenContainer.removeClass('chosen-container-active').removeClass('chosen-with-drop');