2016-09-07 67 views
0

我正在使用以下腳本,如果某人從多個下拉列表中選取了相同的值,則會顯示彈出錯誤。很好的工作,但是在顯示彈出窗口後,重複的選擇仍然會發生。它應該防止這種情況發生。防止在多個下拉列表中重複選擇

$(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

+0

請,寫一些HTML例子。 – Vixed

+0

[jQuery防止更改爲選擇]的可能重複(http://stackoverflow.com/questions/5426387/jquery-prevent-change-for-select) –

+0

檢查此問題,它可能會幫助您找到一個解決方案:http:// stackoverflow.com/questions/4076770/getting-value-of-select-dropdown-before-change一旦你能夠找到以前的值,你只需要改變以前的值的選擇實際值 – Mayday

回答

1

你可以切換到默認選項:

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

希望這有助於。

$(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>

1

一個選項是分配值0,強制選擇新的價值,這樣的事情

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.') 
     } 
    }); 
}); 
+0

這個選項也很棒。 – virs90

相關問題