0

I was wondering if it was possible in php/javascript to prevent duplicate data in multiple select boxes. I've got 6 select boxes in a form where the user can pick numbers between 1 and 36.

What i exactly want is that when the user picks any number such as 12 in the first select box, that number 12 won't appear in the second select box. I've searched all over the internet without a clue.

Taku
  • 31,927
  • 11
  • 74
  • 85

1 Answers1

0

You can check how these function works and make your own solution:

  • Bind an event handler to the "change" JavaScript event, or trigger that event -> jQuery .change()
  • Get the value of a property for the first element in the set of matched elements -> jQuery .prop()

This way is slightly different from other answer as one removes the option, the other disables it.

jQuery part (don't forget to add jQuery in the head of your page)

$(document).ready(function() {
    $(".connSelect").change(function() {

        var selVAL = $(this).val(); // will handle the value of selected item

        $("select option:selected" ).each(function() { // when value is selected
            $("option[value=" + selVAL + "]").prop('disabled', true); // disable on other 'select'
        });
    });
});

HTML part

<select name="select-1" id="select-1" class="connSelect">
    <option value="">-- pick one --</option>
    <option value="1">-- 1 --</option>
    <option value="2">-- 2 --</option>
    <option value="3">-- 3 --</option>
    <option value="4">-- 4 --</option>
    <option value="5">-- 5 --</option>
</select>

<select name="select-2" id="select-2" class="connSelect">
    <option value="">-- pick one --</option>
    <option value="1">-- 1 --</option>
    <option value="2">-- 2 --</option>
    <option value="3">-- 3 --</option>
    <option value="4">-- 4 --</option>
    <option value="5">-- 5 --</option>
</select>

<select name="select-3" id="select-3" class="connSelect">
    <option value="">-- pick one --</option>
    <option value="1">-- 1 --</option>
    <option value="2">-- 2 --</option>
    <option value="3">-- 3 --</option>
    <option value="4">-- 4 --</option>
    <option value="5">-- 5 --</option>
</select>

Here's a FIDDLE to see how it works

NOTE: this is just a example of how-to, and it doesn't perform any verification upon values nor enables values again when disabled

OldPadawan
  • 1,247
  • 3
  • 16
  • 25