I just want to disable a specific option within select element when it is already selected using jQuery.
If a country is already selected in a row, you cannot select it again to different rows, and vice versa. This functionality should also be applied when adding rows.
My problem is even if I added the validation when select on
change
triggered, it is not working, I still can choose the same country.
Please see my code below.
$(document).ready(function() {
$('.btn-add').on('click', function() {
var lastRow = $('table tr.content:last').html();
$('table').append('<tr class="content">' + lastRow + '</tr>');
deleteRow();
$('tr.content:last select.country').val("");
$('select').each(function() {
if ($(this).val() == $('select:selected').val()) {
$(this).attr('disable');
alert("Sorry, you cannot select the same country.");
return false;
}
});
});
$('select.country').on('change', function() {
$('select').each(function() {
if ($(this).val() == $('select:selected').val()) {
$(this).attr('disable');
alert("Sorry, you cannot select the same country.");
return false;
}
});
});
deleteRow();
function deleteRow() {
$('.btn-delete').on('click', function() {
$(this).closest('tr').remove();
});
}
});
.btn-add,
.btn-delete {
padding: 2px;
cursor: pointer;
}
<table class="table">
<thead>
<tr>
<th>Gender</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr class="content">
<td>
<select>
<option class="Male">Male</option>
<option class="Female">Female</option>
</select>
</td>
<td>
<select class="country">
<option class="UK">UK</option>
<option class="US">US</option>
<option class="JP">JP</option>
</select>
</td>
<td>
<span class="btn-delete">Delete</span>
</td>
</tr>
</tbody>
</table>
<br><br>
<span class="btn-add">Add</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>