var abc = new Array('Perth','Auckland');
case '1':
document.getElementById(q15).options.length = 0;
for (i = 0; i < abc.length; i++) {
createOption(document.getElementById(q15), abc[i], abc.[i]);
}
break;
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
The above code outputs the following:
<option value="1">Perth</option>
<option value="2">Auckland</option>
However, I need to add some PHP to calculate if the option is selected when the page loads, so the output should look something like this:
<option value="1" <?php if ($results['abc']==1) echo "selected";?>>Perth</option>
<option value="2" <?php if ($results['abc']==2) echo "selected";?>>Auckland</option>
However, I’m struggling with the Selected option in the Javascript to add this an option and add it to the drop down list.
Any help appreciated.
Thanks,
H.
Two things,
First,
You can set the
selectedattribute using JavaScript by doingdomelement.setAttribute("selected","selected");I think that is what your original question is about.
Second,
You can’t add PHP code using javascript, because PHP runs at the server before your browser gets the code.
I’d use PHP to store the
$resultsvariable into a javascript variable and use that to setselected.