Vinay Vinay - 5 months ago 12
Javascript Question

Hide either one of the option by selected value in javascript?

I have a form with two identical

select
lists like follows:

<select id="system" name="system[1][1]">
Option 1
Option 2
</select>

<select id="system" name="system[1][2]">
Option 1
Option 2
</select>


I want the user select either one of this select
option2
. If user choose
option2
in
first select
then hide the
option2
in
second select
and vice versa.

Example:



var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');

if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}


Which I think is bit of messy. Is it any elegant way that I can achieve this in
Javascript
or
Jquery
?

Thanks

Answer

Try following code :

<select id="system" name="system[1][1]">
    <option value="optioin-1">Option 1</option>
    <option value="option-2">Option 2</option>
</select>

<select id="system" name="system[1][2]">
    <option value="optioin-1">Option 1</option>
    <option value="option-2">Option 2</option>
</select>

jQuery :

jQuery('select').change(function(e){
    var value = $(this).val();
    var selectboxId = $(this).attr('name');
    jQuery('select option').show();
    if(selectboxId == 'system[1][1]') {
        jQuery('select[name="system[1][2]"]').find('option[value="'+value+'"]').hide();
    } else if(selectboxId == 'system[1][2]') {
        jQuery('select[name="system[1][1]"]').find('option[value="'+value+'"]').hide();
    }
});
Comments