Why is the selected <select> option not being cleared using Choosen?

Asked

Viewed 63 times

2

I was trying to clear the selected option from the checkbox - <select> using Javascript. In this checkbox I am using the plugin Choosen.

I saw an answer in Stack Overflow, and I’ve 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');
            };
        });

However I still can’t 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 clear the option selected in the combobox?

  • for????

  • What is it? What problem? @LINQ

  • What is the reason for this tag?

  • I thought it was appropriate @LINQ.

  • But why? I don’t understand the relationship of the question with for

  • tidy up there, I forgot to save

  • https://jsfiddle.net/bxuxk9p2/4/

Show 2 more comments

2 answers

5


You are selecting the index of loop not the page entry, see if the code below works:

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

0

The logic is correct, however, you forgot to include your variable cmb at the loop. Notice that you didn’t use it on loop itself, simply stated it, but within the loop, you didn’t use it:

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

You can add it, inside the loop, and together with the variable i, access the contents of your array each iteration, to be replaced by the elements of array, in that way:

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

Finally, you can do as follows, 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');
            };
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.