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?
$('#my_select'). bind('change', function(ev) { if(my_condition) { ev. preventDefault(); return false; } });
if(confirm('sure? ')){ //do sth; }else{ this. selectedIndex = 0; // if cancel the confirm window, option remains as unchanged. }
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"); });
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')); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With