duanlieshuang5330 2011-11-28 18:32
浏览 87
已采纳

使用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>
  • 写回答

4条回答 默认 最新

  • duanmeng3573 2011-11-28 18:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog