使用PHP通过Javascript选择选项值

Ok, so here is my code. I am trying to select a picklist value using Javascript, from PHP (I do not want a direct method to do this with PHP, as this won't work for my particular program)

Here's the code:

ECHO '<script type="text/javascript">
    var pl = document.getElementById("cultpicklist");
 pl.options[37].selected = true;
 </script>';

However when I try to run this, it does not seem to work and it says pl.options[37] is undefined.

What am I doing wrong?

Note, there is a multiple select list which has an option with a value of 37.

EDIT: I seem to get this error or warning message:

Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
admin.php?org=7()admin.php?org=7 (line 68)
pl.options[37].selected = true;

Here's the relevant HTML:

<fieldset><label for="culture">Culture:</label>
        <select name="culture[]" multiple="multiple" id="cultpicklist"><?php
    while ($cultrow = mysql_fetch_array($rescult)) {
        ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
    }
    ?>
        </select></fieldset>

Here's the generated HTML code:

<select id="cultpicklist" multiple="multiple" name="culture[]">
<option value="36" name="culture[]">test1</option>
<option value="37" name="culture[]">test2</option>
<option value="38" name="culture[]">test3</option>
<option value="39" name="culture[]">test4</option>
</select>

The index of the options IS NOT the value of the option. When you use pl.options[37] you saying to JS to get the thirty-seventh option in the select and not the option with the value 37.

Try this:

<script type="text/javascript">
    var pl = document.getElementById("cultpicklist");
    for(var i=0; i<pl.options.length;i++) {
        if(pl.options[i].value == "") { // Between the quotes you place the comparison value!
            pl.options[i].selected = true;
        }
    }
</script>

BTW: If you already use jQuery on your page it's more correct to use it's functions, but if you don't use jQuery is too much code to add to your page just to change a select value.

You are likely putting the cart before the horse. You cannot use JavaScript to manipulate DOM elements until they've been rendered in the browser.

Put your script AFTER your HTML or check to see of the DOM is ready before running your script.

Why not use JQuery first of all...

$('#cultpicklist').val('myvaluetoselect');

Is MUCH easier to code, read and works instead of using bulky old school javascript...

Using jQuery, you could still put your code in between <head></head> tags. You would use $(document).ready() thus executing your code after the whole document has rendered.