JavaScript: get dropdown value
Don't use jQuery for this:
function getSelectValues() {
var values = [];
for (var i = 0; i < arguments.length; i++) {
var select = document.getElementById(arguments[i]);
if (select) {
values[i] = select.options[select.selectedIndex].value;
} else {
values[i] = null;
}
}
return values;
}
This function returns an array of values ββthat match id
that you pass to the function as follows:
var selectValues = getSelectValues('id1', 'id2', 'id3');
If a <select>
with one of the ones you specified id
does not exist, the array contains null
for the value for that position.
There are several other ways to do this, you could pass an array of id
values to the function getSelectValues([ 'id1', 'id2', 'id3' ])
, in which case the function will be changed:
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
You can also pass a map to the function id
and fill in the values:
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
This will change the function:
function getSelectValues(map) {
for (var id in map) {
var select = document.getElementById(id);
if (select) {
map[id] = select.options[select.selectedIndex].value;
} else {
map[id] = null;
}
}
}
source to share
I would try to set them next to each other in your HTML and then loop through them using the built-in jQuery method. You would create your elements like this:
<div id="dropdownBoxes">
<select id="firstElement">
<option>cool</option>
<option>neat</option>
</select>
<select id="secondElement">
<option>fun</option>
<option>awesome</option>
</select>
<select id="thirdElement">
<option>great</option>
<option>synonym</option>
</select>
</div>
<input type="button" id="theTrigger">Push me!</input>
Then in your script:
var dropdownValues;
$("#theTrigger").click(function(){
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
dropdownValues.push($(this).val());
});
});
source to share