Non-repeatitive Dropdown Select
I have 4 select dropdown and i want each selection to be non-repeatitive or cannot be selected twice. Step 1 - If i select two from DROPDOWN 1,all selection number two from the oth
Solution 1:
$( document ).ready(function() {
$('select').on('change', function() {
selected = [];
$('select').each(function() {
if ($(this).val() !== "No Match")
selected.push($(this).find('option:selected').val());
});
console.log(selected);
$('select').children().each(function(index) {
if ($.inArray($(this).val(), selected) !== -1) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label>DROPDOWN 1</label><selectname="select1"><option>No Match</option><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option><optionvalue="4">Four</option></select><br><label>DROPDOWN 2</label><selectname="select2"><option>No Match</option><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option><optionvalue="4">Four</option></select><br><label>DROPDOWN 3</label><selectname="select3"><option>No Match</option><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option><optionvalue="4">Four</option></select><br><label>DROPDOWN 4</label><selectname="select4"><option>No Match</option><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option><optionvalue="4">Four</option></select>
Here is idea -> on each dropdown change, itterate through all dropdowns, including current, and (re)create array of selected options, then iterate through every children (options), and set attribute accordingly.
$('select').on('change', function() {
selected = [];
$('select').each(function() {
if ($(this).val() !== "No Match")
selected.push($(this).find('option:selected').val());
});
console.log(selected);
$('select').children().each(function(index) {
if ($.inArray($(this).val(), selected) !== -1) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
});
Demo: https://jsfiddle.net/g3t3v22o/
P.S. Array re-creation is needed, in case that user changes his mind (while he can do it, while there are some options left). Check console.log, to see how selected array is changed, during process...
Post a Comment for "Non-repeatitive Dropdown Select"