coure2011
coure2011

Reputation: 42414

jquery chosen before change event

I want to capture a before change event of jquery chosen, so if the value clicked in chosen is not the required one, it just do nothing and go back to previous selected option. Is it possible?

something like

$('.chzn-select').chosen({
    'beforeChange': function(){
        //if option clicked is Option-3
        //do nothing

    }
});

Upvotes: 0

Views: 9710

Answers (2)

letiagoalves
letiagoalves

Reputation: 11302

With the help of data jQuery function, change event and params.selected argument you can easily achieve that.

$(".chzn-select").chosen().on("change", function (evt, params) {
    if (params.selected === "Portugal") {
        var previous = $(this).data("previous") || "";
        $(this).val(previous).trigger("chosen:updated");
    } else {
        $(this).data("previous", params.selected);
    }
});

See this working demo

Upvotes: 6

Clyde Lobo
Clyde Lobo

Reputation: 9174

Something like this

(function () {
    var previous;    
    $(".chzn-select").focus(
        function () {
    // Store the current value on focus and on change
        previous = $(this).val();
    }).change(function() {
        if($(this).val()=="Option-3"){// //if option clicked is Option-3
            $(this).val(previous); // select the value prior to the change
            $(this).trigger("chosen:updated"); // tell chosen to pick up the updated value      
        }
    });
})();

I have taken the idea from : Getting value of select (dropdown) before change

Upvotes: 1

Related Questions