I would make a function that checks every selected value, and then enables all option
s, searches through the .staff_list
s for option
s in that array that are not currently selected, and disables them all.
Add that function as a listener to the wrapper
(with event delegation) and run it after more <select>
s are appended (to ensure the new options' values get properly disabled), and run it after <select>
s are deleted (so that if that <select>
had anything selected, its value is now enabled again in the other elements).
This ensures a correct re-calculation of disabled option
s whenever there's a change.
Note that because there are currently only 3 possible values (a
, b
, and c
), only three select
s can currently be changed - after that, every possible option (except the default) will be disabled.
var add_button = $(".add_sign");
var wrapper = $(".sign");
var max_fields = 6;
var x = 1;
add_button.click(function(e) {
if (x < max_fields) {
x++;
wrapper.append('<div class="input-group sign_user"><select class="staff_list" name="staff_id"><option value="">--Select staff--</option><option value="a">A</option><option value="b">B</option><option value="c">C</option></select><span class="input-group-btn delete_sign"><a href="#" class="btn btn-sm btn-danger">X</a></span></div>');
recalcDisabled();
} else {
alert('Maximum 5 Authorised Signatory only!');
}
});
//Delete staff_list
$(wrapper).on("click", ".delete_sign", function(e) {
e.preventDefault();
$(this).parent('div').remove();
recalcDisabled();
x--;
});
wrapper.on('change', 'select', recalcDisabled);
function recalcDisabled() {
const selectedValues = $('.staff_list')
.map((_, sel) => sel.value)
.get()
.filter(Boolean); // Filter out the empty string
$('.staff_list option').prop('disabled', false);
selectedValues.forEach(value => {
$(`.staff_list[value!="${value}"] option[value="${value}"]`)
.prop('disabled', true);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sign">
<button class="add_sign">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span> </button>
</div>
Credit: CertainPerformance (https://stackoverflow.com/users/9515207/certainperformance)
No comments:
Post a Comment
Please Comment Here!