Dynamically disable select menu based on text field value

I’d like to be able to disable a select menu on my page when a user starts typing in a text field. This is because the text field is an alternative way to enter the data and disabling the dropdown menu will help make that clearer.

I know I could use this:

<select name="specialty" id="specialty" disabled="disabled">

to disable the select permanently, but is there a way to assign that attribute dynamically when the value of a text field changes? I know there is no css property to do it like there is for text inputs and textareas.

Something I found is a JQuery solution for disabling options within a select:

Disable select options based on value *through the HTML only!*

I tried modifying this to disable the whole select but with no success (id of text field is testinput):

<script type="text/javascript">

$("#testinput").change(function(){
    $("#specialty").attr("disabled","disabled");
}
);

</script>

This is a simplified version (the real function should check the length of the string in testinput and decide whether to disable or enable the select based on that), but if someone can help me get this working, then modifying it is easy.

Answer

For me, it works if the event handler is declared after the DOM is ready:

<script type="text/javascript">

$(document).ready(function() {
$("#testinput").change(function(){
    $("#specialty").attr("disabled","disabled");
}
);
});

</script>

However, this way the selectbox will only disable after the input box has lost focus. You might want to use one of the key press events instead.

Leave a Reply

Your email address will not be published. Required fields are marked *