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


Trying to get Javascript to select each child from a multiple select box

我正试图使用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。

修复了它。其中

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

等等,应该是

$parent

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