试图让Javascript从多个选择框中选择每个孩子

时间:2012-01-20 14:02:13

标签: php javascript mysql

我正在尝试使用PHP来让Javascript在多个选择框中选择取决于特定GET的值。

这是我的代码:

if (isset($_GET["parent"])  && ($_GET['parent'] !== '')) {
    $parent = $_GET['parent'];

    echo '<script type=text/javascript>
        document.getElementById("locpick").value="'.stripslashes($parent).'";
            </script>';


$reschild = mysql_query("SELECT child_id from loc_child_xref where loc_id='".$locrow['loc_id']."'");
while ($childrow = mysql_fetch_array($reschild)) {
    $childloc = mysql_query("SELECT loc_id, loc_desc from location where loc_id='".$childrow['child_id']."'");
    while ($childlocrow = mysql_fetch_array($childloc)) {
        echo '<script type="text/javascript>
            var pl = document.getElementById("child");
        for(var i=0; i<pl.options.length;i++) {
        if(pl.options[i].value == "' . stripslashes($childlocrow['loc_id']).'") {
            pl.options[i].selected = true;
            }
            }
            </script>';
            }

}  
}

它选择第一个id,但不选择第二个id。

2 个答案:

答案 0 :(得分:1)

修正了它。

loc_id='".$locrow['child_id']."' 

等等,应该是

$parent

答案 1 :(得分:0)

我很高兴你修好了,但我同意@DaveRandom。您的代码会为结果集中的每个<script>输出一个新的$childlocrow。更简洁的解决方案是使用PHP将selected="selected"添加到相关的<options>。但是,如果这不可能,您应该将echo id考虑到JavaScript数组并对其执行检查。这样,您只需要一个<script>块。