I am trying to add options to select element using javascript dynamically for a university assignment.
We are creating a class booking system for a gym so users can book into a class. I wanted to use drop down boxes, so you select the class, then the time using the next drop down box, so it has to change depending on the class selected. Finally, the user would select the personal trainer in the last box, once again created depending on what timeslot is selected.
This is what I have so far (javascript side):
<script type="text/javascript">
function getTimes()
{
var index=document.getElementById("classes").selectedIndex;
var x=document.getElementById("schedule");
if(index==0)
{
document.getElementById("schedule").value=" ";
}
else if(index==1)
{
var option=document.createElement("option");
option.text="Monday 8:00pm";
try
{
// for IE earlier than version 8- from w3 schools
x.add(option,x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
}
and html:
<div>
<span class="label">Class:</span>
<select class="dropdown" id="classes" name="classes" onChange="getTimes();">
<option value="none"> </option>
<option value="pilates">Pilates</option>
<option value="crossfit">Cross Fit</option>
</select>
</div>
<div>
<span class="label">Time:</span>
<select class="dropdown" id="schedule"></select>
</div>
<div>
<span class="label">Trainer:</span>
<select class="dropdown" id="trainer"></select>
</div>
To the code seems like it should work, but for whatever reason when I select the first class, in this case "Pilates" the "Time" drop down box is still blank.
Can anyone tell me where I am going wrong?