javascriptjqueryeventsselect

jQuery prevent change for select


I want to prevent a select box from being changed if a certain condition applies. Doing this doesn't seem to work:

$('#my_select').bind('change', function(ev) {
  if(my_condition)
  {
    ev.preventDefault();
    return false;
  }
});

I'm guessing this is because by this point the selected option has already changed.

What are other ways of doing this?


Solution

  • Try this:

    http://jsfiddle.net/qk2Pc/

    var my_condition = true;
    var lastSel = $("#my_select option:selected");
    
    $("#my_select").change(function(){
      if(my_condition)
      {
        lastSel.prop("selected", true);
      }
    });
    
    $("#my_select").click(function(){
        lastSel = $("#my_select option:selected");
    });