Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 870
overgroove Avatar asked Mar 24 '11 22:03

overgroove


People also ask

How to prevent dropdown change event in jquery?

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

How do you avoid changing select box value if you say no to confirm?

if(confirm('sure? ')){ //do sth; }else{ this. selectedIndex = 0; // if cancel the confirm window, option remains as unchanged. }


2 Answers

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"); }); 
like image 178
mattsven Avatar answered Oct 02 '22 12:10

mattsven


In the event someone needs a generic version of mattsven's answer (as I did), here it is:

$('select').each(function() {     $(this).data('lastSelected', $(this).find('option:selected')); });  $('select').change(function() {     if(my_condition) {         $(this).data('lastSelected').attr('selected', true);     } });  $('select').click(function() {     $(this).data('lastSelected', $(this).find('option:selected')); }); 
like image 42
dwallace Avatar answered Oct 02 '22 12:10

dwallace