如何将select选项中的数组值用作url中的参数?

时间:2018-05-27 22:07:48

标签: javascript php html mysql

我有一个下拉菜单,填充了SQL中的表的结果。我想要做的是获取选择的任何选项的值,并将其作为参数添加到URL中,以便我可以从另一个页面调用它。我似乎无法让它发挥作用。

$sql = "SELECT name FROM lakes";
$result = mysql_query($sql);

echo "<script>";
echo "var sel = document.getElementById('lakes');";
echo "sel.onchange = function () ";
{
echo "    document.getElementById(\"abc\").href = this.value + \".html\";";
}
echo "</script>";

echo "Lakes in the Frost Centre: ";
echo "<div id=\"lakes\" name=\"lakelist\">";
echo "<select onchange = \"redirect(this.value)\" class=\"required\" data- 
val=\"true\" id=\"lakes\" name=\"lakes\">";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
echo "<div class=\"lake-button\">";
echo "    <a id=\"abc\" href=\"lakes/?name=\" + > View Lake </a>";
echo "</div>";

1 个答案:

答案 0 :(得分:0)

假设$row = mysql_fetch_array($result)没有错误,你应该这样做:

$sql = "SELECT name FROM lakes";
$result = mysql_query($sql);


echo "<script>";
echo "var sel = document.getElementById('lakes');";
echo "function redirect(value) {"; //is already the selected value (this.value)
{
    echo 'document.getElementById("abc").href = "lakes/?name="+value+".html";}';
}
echo "</script>";

echo "Lakes in the Frost Centre: ";
echo '<div id="lakes" name="lakelist">';
echo '<select onchange = "redirect(this.value)" class="d" data- 
val="true" id="lakes" name="lakes">';

while ($row = mysql_fetch_array($result)) 
echo '<option value=' . $row['name'] . '>' . $row['name'] . '</option>';
}

echo "</select>";
echo '<div class="lake-button">';
echo '    <a id="abc" href="lakes/?name=" + > View Lake </a>';
echo '</div>';

请记住'是文字的,必须声明onchange调用的函数。

另请注意,如果某些用户选择默认选项(Lake1或其他),onchange不会触发任何事件。然后,您应该包含一些选项,如<option>Select whatever..</option>,以便触发所有选项的事件。