remove select options from other selects

1

Well, I have 4 html selects and in all of them I have the same options, I wanted that when an option of the first select was selected it would be disabled in the other selects, it is possible to do it efficiently and quickly with jquery?

    
asked by anonymous 28.10.2017 / 16:48

2 answers

2

The simplest option is to catch the 'change' event of the select, cycle it from there help:

HTML

<select name="select1">
    <option>default</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<select name="select2">
    <option>default</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

JQUERY

$(document).ready(function(){

    $('select').change(function() {

        var value = $(this).val();

        $(this).siblings('select').children('option').each(function() {
            if ( $(this).val() === value ) {
                $(this).attr('disabled', true).siblings().removeAttr('disabled');   
            }
        });

    });

});
  

Given a jQuery object that represents a set of DOM elements, the    .siblings () method allows us to search through siblings of these   elements in the DOM tree and construct a new jQuery object from the   corresponding elements. See more

Example to work.

    
28.10.2017 / 17:20
1

I put all select tags in an array to iterate later

var selects = document.getElementsByTagName("select");

I say that when the select changes the value, calling the following function

selects[i].onchange = function(e) {

Except the current value of the select separately only for clarity as it did not need to, since the rest is in the same scope var val = this.value;

Now I look at all selects if any already have the same value that was selected now

for (var z = 0; z < selects.length; z++) {

Here I need the position of the current select, since you need verification to occur in the others

var index = Array.prototype.indexOf.call(selects, this);

Here I verify if it is not the current select and if the selected value is equal to the current

if ((z !== index) && selects[z].value === val) {

Now I'll deselect the selected option tag

for (var o = 0; o < options.length; o++) {
    if (options[o].selected) {
        options[o].selected = false;
    }

Here I re-select the first pattern (What is your vacation option?)

options[0].selected = true;
    
28.10.2017 / 17:16