Why is not the selected select option being cleaned using Choosen?

2

I was trying to clear the selected option from the - <select> check box using JavaScript. In this checkbox I'm using the Choosen plugin.

I saw an answer in the Stack Overflow , and I already made the following code:

$("#btnLimpar").click(function(){
            $("#editPublication")[0].reset();
            var cmb = new Array('#cmbCompany','#cmbType','#cmbTitle','#cmbEmployee','#cmbMonth');

            for (var i = 0; i < cmb.length; i++) {
                $(i).val('').trigger('chosen:updated');
            };
        });

I still have not been able to clear the selected option. And if I use:

console.log($(i).val('').trigger('chosen:updated'));

Information similar to this is returned:

r.fn.init {}
    __proto__: Object(0)

 [1]
    0: 1
    length: 1
    __proto__: Object(0)

How can I clean the selected option in the combobox ?

    
asked by anonymous 28.09.2017 / 21:40

2 answers

5

You are selecting the loop index and not the element on the page, see if the code below works:

$("#btnLimpar").click(function(){
    $("#editPublication")[0].reset();
    $("#cmbCompany,#cmbType,#cmbTitle,#cmbEmployee,#cmbMonth").val("").trigger("chosen:updated");
});
    
28.09.2017 / 22:10
0

The logic is correct, however, you forgot to include your variable cmb to loop . Note that you did not use it in the loop itself , simply stated it, but within the loop , you did not use it:

$(i).val('').trigger('chosen:updated');

You can add it within the loop , and along with the i variable, access the indexes of your array at each iteration, so that it is replaced by the array elements, like this:

$(cmb[i]).val('').trigger('chosen:updated');

Finally, you can do the following, which will work:

$("#btnLimpar").click(function(){
            $("#editPublication")[0].reset();
            var cmb = new Array('#cmbCompany','#cmbType','#cmbTitle','#cmbEmployee','#cmbMonth');

            for (var i = 0; i < cmb.length; i++) {
                $(cmb[i]).val('').trigger('chosen:updated');
            };
});
    
29.09.2017 / 15:35