我有不同的選擇與相同的內容,我想要控制,用戶不會把相同的值在兩個或更多的選擇,我讓這個代碼,但我認爲有一些選擇比這更好,我把這裏的代碼分享,同時詢問是否存在一些更好的選擇。因爲我搜索這樣的解決方案,我找不到。不允許重複在不同的HTML選擇與JavaScript或JQuery相同的內容
$(function() {
function restrict_multiple(selector) {
// Here sets the current value in your alt
$(selector).each(function() {
$(this).attr("alt", $(this).val());
})
// trigger when the select change
$(selector).change(function() {
// Remove the hidden from the <option>
$(selector + " option").removeClass("hidden");
// I use thr alt attr, like an aid to maintain the actual selected value
$(this).attr("alt", $(this).val())
// Create an array with the selected options
var selected = new Array();
// Every selected option is assigned into this array
$(selector + " option:selected").each(function() {
selected.push(this.value);
})
// Apply the hidden the other select options
for (k in selected) {
if(selected[k] != ""){
$(selector + "[alt!=" + selected[k] + "] option[value=" + selected[k] + "]").addClass("hidden")
}
}
})
// trigger to keep updated all selects
$(selector).each(function() { $(this).trigger("change"); })
}
//calling the function again sending the class
restrict_multiple(".excluyent-select");
})
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="participantes_1" id="participantes_1" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
<select name="participantes_2" id="participantes_2" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
在這裏,我把鏈接給一些例如運行:http://jsfiddle.net/hevercking/xdmd87se/
這將有助於如果代碼註釋是在默認的堆棧溢出語言(即英文:) :) – 2014-11-06 16:59:31
哎呦,對不起TrueBlueAussie我沒有注意到,我直接把它放在 – hevercking 2014-11-06 17:16:26
評論在英語:)對不起這布盧姆 – hevercking 2014-11-06 17:28:07