delete select options from other selects

Asked

Viewed 121 times

1

Good, I have 4 html selects and in all of them I have the same options, I wanted when selecting an option from the first select that same option was placed as disabled in the other selects is possible to do this efficiently and quickly with jquery?

  • But only the first <select> is that disables options in others, the reverse does not happen ?

  • yes the reverse also happens, thank you for the reminder

2 answers

2


Simplest option is to capture the 'change' event from the select, to cycle from there the siblings helping:

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 representing a set of DOM elements, the .siblings() method allows us to search through the brothers of these elements in the DOM tree and build a new jQuery object from the corresponding elements. See more

Working example.

1

I put all select tags in an array to iterate afterwards

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

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

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

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

Now I search in all selects if any already has the same value that was selected now

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

Here I need the position of the current select, because you need the check to occur in others

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

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

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

Now I will deselect the selected tag option

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

Here I select the first pattern again (What is your holiday option?)

options[0].selected = true;
  • where this i ? selects[i].onchange

Browser other questions tagged

You are not signed in. Login or sign up in order to post.