1

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

virs90
  • 149
  • 2
  • 12

2 Answers2

4

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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

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.')
        }
    });
});
AitorFDK
  • 101
  • 6