In the application I am making, I have several dropdown lists (more than 10). I having trouble getting the results of each dropdown list on a button click. I need an iterative way to get the options selected by the user from each dropdown.
I am able to get the values from one dropdown using the following:
let drops = [];
$(document).delegate("select", "change", function() {
var values = $('#drop1').val(); // type of array
drops = values;
});
console.log(drops);
But I need an iterative way to get the selected values from all dropdowns. Here is my attempt:
$('#btner').click(function() {
var values;
$('#container > .d-flex > select').each(function() {
let id = $(this).attr('id'); //gets id of each dropdown
$(document).delegate("select", "change", function() {
values = $('#' + id).val(); // type of array
});
console.log(values);
});
})
Here is the general structure of my code.
new TomSelect('#drop1', {
sortField: 'text',
hideSelected: false,
duplicates: true,
plugins: ['input_autogrow'],
});
new TomSelect('#drop2', {
sortField: 'text',
hideSelected: false,
duplicates: true,
plugins: ['input_autogrow'],
});
new TomSelect('#drop3', {
sortField: 'text',
hideSelected: false,
duplicates: true,
plugins: ['input_autogrow'],
});
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/tom-select.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/tom-select.complete.min.js"></script>
</head>
<body>
<div id="container">
<div class="d-flex" id="menuItems" style="width: 58%;">
<select id="drop1" style="width: 100%;" multiple data-mdb-option-height="44">
<option value="" disabled selected>Select</option>
<option value="Item1">Item1</option>
<option value="Item2">Item2</option>
<option value="Item3">Item3</option>
</select>
</div>
<br><br>
<div class="d-flex" id="menuItems" style="width: 58%;">
<select id="drop2" style="width: 100%;" multiple data-mdb-option-height="44">
<option value="" disabled selected>Select</option>
<option value="Item4">Item4</option>
<option value="Item5">Item5</option>
<option value="Item6">Item6</option>
</select>
</div>
<br><br>
<div class="d-flex" id="menuItems" style="width: 58%;">
<select id="drop3" style="width: 100%;" multiple data-mdb-option-height="44">
<option value="" disabled selected>Select</option>
<option value="Item7">Item7</option>
<option value="Item8">Item8</option>
<option value="Item9">Item9</option>
</select>
</div>
</div>
<!-- Button -->
<br> <br>
<button id="btner" type="button" class="btn"> Sumbit </button>
</body>
</html>
on()which it will already use under the hood