0

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

    }
});
coure2011
  • 34,326
  • 71
  • 200
  • 319

2 Answers2

6

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

letiagoalves
  • 10,718
  • 4
  • 37
  • 66
1

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

Community
  • 1
  • 1
Clyde Lobo
  • 8,747
  • 6
  • 34
  • 58