I want to prevent a select from being changed when a specific condition is satisfied without disabling the select element.
There are two events that detect changes to input , textarea , and select elements: change and input . The change event feels like it would be the right one, but it only fires when focus leaves the field. To detect real-time changes, you want the input event.
First of all onfocus is called. This event keeps the current value in a attribute "PrvSelectedValue". Secondly onchange is called, we set the previous value if user cancel the confirmation popup. return false is used to prevent the postback in ASP.NET.
The hidden attribute hides the <option> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <option> element is not visible, but it maintains its position on the page.
Styling the option partSeveral CSS properties can be used to change the appearance of an option, and some properties applied to the <select> element are inherited too. For example, it's possible to change the color and font of the <option> elements to match your website's appearance.
Try this: JSBin Demo
<select id="mySelect" data-value="" onfocus="this.setAttribute('data-value', this.value);"
onchange="this.value = this.getAttribute('data-value');">
You can hold last
changed value of select and reassign
it when you do not want use to change the select under your condition.
Live Demo
Html
<select id="select">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Javascript
preval = $('#select').val();
$('#select').change(function() {
if ($(this).val() == "2") { $(this).val(preval); return;}
preval = ($(this).val();
});
old_value = $('#select :selected').val();
$('#select').change(function() {
if($(this).val() == 'option 3') {//your specific condition
$('#select').val(old_value);
} else {
old_value = $('#select :selected').val();
}
});
demo
Example of what you want to do
var select = $('select'), option = $('whatyouwanttotest');
if (option.val() == 'value') {
select.attr('disabled', 'disabled');
} else {
select.removeAttr('disabled');
}
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