Reputation: 3323
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.
Upvotes: 2
Views: 335
Reputation: 935
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>*/
Upvotes: 1
Reputation: 46
Where is $results
coming from? If it's something you are operating on in the PHP logic during page creation, then I assume you're specifically asking about why the select item isn't properly being selected?
<option value="1" <?php if ($results['abc']==1) echo "selected";?>>Perth</option>
That should actually be setting the selected attribute to the value "selected" (rather than just printing selected word alone). So, it should be:
<option value="1" <?php if ($results['abc']==1) echo "selected=\"selected\"";?>>Perth</option>
Upvotes: 0