Reputation: 6471
I am adding a row to my datatables by selecting an option from my selectbox:
<select class="item-select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
$(document).on('change', '.item-select', function() {
var optionValue = $(this).val();
var optionText = $('.item-select option[value="'+optionValue+'"]').text();
table.row.add({
"id": optionValue,
"name": optionText,
}).draw();
});
It is working well, but I want to be able to add the same option directly once again.
This means for example: I add Volvo
, then I add Saab
, but when I want to add now another Saab
it is not working. I have to add something else like VW
, and then I am able to add Saab
.
Upvotes: 0
Views: 176
Reputation: 2759
Add a blank value and reset the select which won't trigger the change
event.
$(document).on('change', '.item-select', function() {
var optionValue = $(this).val();
var optionText = $('.item-select option[value="'+optionValue+'"]').text();
if (optionValue) {
// table.row.add({
// "id": optionValue,
// "name": optionText,
// }).draw();
$('option', this).first().prop('selected', true)
console.log(`${optionText} added`)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="item-select">
<option>Select make...</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
Upvotes: 1