virs90
virs90

Reputation: 149

Prevent duplicate choice in multiple dropdowns

I'm using the following script which displays a pop-up error if a person has picked same values from multiple drop-downs. Works great, however after showing the pop-up, the duplicate selection still takes place. It should prevent this from happening.

$(document).ready(function () {
    $('select').change(function () {
        if ($('select option[value="' + $(this).val() + '"]:selected').length > 1) {
            alert('You have already selected this option previously - please choose another.')
        }
    });
});

jsfiddle example here

Upvotes: 1

Views: 5232

Answers (2)

AitorFDK
AitorFDK

Reputation: 101

One option is assign value 0 to force to select new value, something like this

jQuery(document).ready(function () {

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

        if ($('select option[value="' + $(this).val() + '"]:selected').length > 1)
        {
            $(this).val(0);
            alert('You have already selected this company - please choose another.')
        }
    });
});

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could switch to the default option :

$(this).val('-1').change();

Hope this helps.

$(document).ready(function () {
  $('select').change(function () {
    if ($('select option[value="' + $(this).val() + '"]:selected').length > 1) {
      $(this).val('-1').change();
      alert('You have already selected this option previously - please choose another.')
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value='-1'>Choose an option</option>
  <option value='1'>option 1</option>
  <option value='2'>option 2</option>
  <option value='3'>option 3</option>
</select>

<select>
  <option value='-1'>Choose an option</option>
  <option value='4'>option 4</option>
  <option value='1'>option 1</option>
  <option value='5'>option 5</option>
</select>

Upvotes: 4

Related Questions