imbagila
imbagila

Reputation: 513

How to disable <select> option based on other <select> option selected?

There is 2 combobox with the same options as well as the value. So when the user selected python in first combobox, the python option in second combobox will be disable. But when I try this is wouldn't work. Here is my code :

HTML :

<select name="first_combobox">
    <option value="python">Python</option>
    <option value="ruby">Ruby</option>
    <option value="lua">Lua</option>
</select>

<select name="second_combobox">
    <option value="python">Python</option>
    <option value="ruby">Ruby</option>
    <option value="lua">Lua</option>
</select>

JS (jQuery) :

$("select[name=first_combobox]").change(function(){
    if ($("select[name=first_combobox]").val() === $("select[name=second_combobox]").val()) {
        $("select[name=second_combobox] option[value=" + $("select[name=first_combobox]").val() + "]").attr("disabled", "disabled");
    } else {
        $("select[name=second_combobox] option[value=" + $("select[name=first_combobox]").val() + "]").removeAttr("disabled");
    }
});

Can someone help me to solve this? Thanks before

Upvotes: 1

Views: 1642

Answers (2)

HenryDev
HenryDev

Reputation: 4953

This should do exactly want you need. Hope it helps!

$(document).ready(function(){
		$("#theSelect").change(function(){
			$("select[name=second_combobox] option").removeAttr("disabled");
			$("select[name=second_combobox] option[value=" + $("select[name=first_combobox]").val() + "]").attr("disabled", "disabled");
		});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<select id = "theSelect" name="first_combobox">
	<option value="python">Python</option>
	<option value="ruby">Ruby</option>
	<option value="lua">Lua</option>
</select>

<select id="theSelect" name="second_combobox">
	<option value="python">Python</option>
	<option value="ruby">Ruby</option>
	<option value="lua">Lua</option>
</select>

Upvotes: 0

Xzandro
Xzandro

Reputation: 977

This should work for you:

$("select[name=first_combobox]").change(function(){
    $("select[name=second_combobox] option").removeAttr("disabled");
    $("select[name=second_combobox] option[value=" + $("select[name=first_combobox]").val() + "]").attr("disabled", "disabled");
});

Fiddle

Upvotes: 2

Related Questions