Hi I have the following code for appending comboboxes when button is clicked.
I want to check if the value is selected in any previous combobox if it is selected then alert "value is already selected".
For example, I have 5 comboboxes appended and the value in each combobox should be different from each other by traversing each value in the comboboxes:
<div class="custom-control custom-checkbox">
<input type="checkbox" class="itemRow custom-control-input" id="itemRow_1">
<label class="custom-control-label" for="itemRow_1"></label>
</div>
<div class="form-group has-success">
<select name="proid[]" class="form-control" id="proid_1" required="required">
</select>
</div>
<div class="form-group has-success">
<button type="button" name="addbtn" id="addbtn" class="btn btn-success">Add Product</button>
</div>
JQUERY CODE
var count = $(".itemRow").length;
$(document).on('click', '#addbtn', function() {
count++;
var productcombo='';
productcombo += '<tr>';
productcombo +='<td><input type="checkbox" class="custom-control-input itemRow" id="itemRow_'+count+'"> <label class="custom-control-label" for="itemRow_'+count+'"></label> </td>';
productcombo +='<td><select name="proid[]" class="form-control" id="proid_'+count+'" required="required"> </select></td>';
productcombo += '</tr>';
$('#products').append(productcombo);
});
$("#proid_"+count).change(function()
{
var id = $(this).find(":selected").val();
// code here to compare each value
if(value found in previous comboboxes)
{
alert("Already Selected");
}
});
You can set an array variable and when user select a value of combobox, push the value in it.
var selectedVals = [];
$("#proid_"+count).change(function() {
var id = $(this).find(":selected").val();
// code here to compare each value
if(selectedVals.includes(id)) {
alert("Already Selected");
} else {
selectedVals.push(id);
}
});