Bassem Sameh Bassem Sameh - 1 year ago 39
Javascript Question

How to iterate through multiple dropdown lists and access their option values

I'm writing the code for a basic GPA calculator. Basically, it's a 3-column-table, two text areas for the course name/credit hours and a dropdown list that contains letter grades (A+, C, B-) and their corresponding point values as the option value, like this

<td><select name="letterGrades">
<option value="0.7">A+</option>>
<option value="1.3">A-</option>>
<option value="2.7">C+</option>
</option>
</select>
</td>


I need to iterate through the rows, get the option value or "grade" for each course.

var table = document.getElementById(tableID);

for(var i=0; i<rowCount; i++) {

grade = table.rows[i].cells[2].options[letterGrades.selectedIndex].id; //is this allowed?
credits = parseFloat(table.rows[i].cells[1].value);
totalHours += parseFloat(table.rows[i].cells[1].value);
perCourse += grade*credits

}

totalGPA = perCourse/totalHours;


I realize there are other ways to assign the letters to their point values (arrays?) but I still don't know how to iterate through the dropdown lists and get their option values.

Answer Source

Get to the <select> items first. If that's possible, I suggest you use document.getElementsByTagName('select') to get the list of all <select> tags on your page. Then, with each <select> tag, call theSelectTag.getElementsByTagName('option') (where theSelectTag is an object from the returned node list). You can then access their value through the value property (ya rly), and their label through the textContent property.

getElementsByTagName returns a NodeList object, but you can pretty much treat it the same as an Array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download