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 selected
attribute using JavaScript by doing domelement.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 $results
variable into a javascript variable and use that to set selected
.
var results = ["<?php echo implode ('","', $results); ?>"] /*Get the results array from PHP to javascript.*/
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);
/*add the "selected" attribute to options that results['abc'] == <number>*/