I have 3 HTML combo/drop down boxes. All of them have a distinct name and id. On a particular event I want to get the value of all three of them. Can any one give me a code snippet for that?
Use a framework like jQuery mentioned above or just do it the old school way. document.getElementById('dropdownId').value
.
To do this not using jQuery:
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 correspond to the id
s you pass into the funtion, as follows:
var selectValues = getSelectValues('id1', 'id2', 'id3');
If a <select>
with one of your specified id
s does not exist the array contains null
for the value for that position.
There are a couple of other ways to do this, you could pass the function an array of id
values: getSelectValues([ 'id1', 'id2', 'id3' ])
, in which case the function would be changed:
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
You could also pass the function a map of id
s and populate the values:
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
This would change the function to be:
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;
}
}
}
I'd try to set them up next to each other in your HTML and then iterate through them using jQuery's built-in each() method. You'd set up 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());
});
});