使用选择值进行表单操作

时间:2012-02-03 18:25:37

标签: php forms select drop-down-menu

我有一个下拉列表,我想使用选项下拉列表的值来确定post方法表单操作的目的地。

<form name="scriptform" method="post" action=http://www.mysite.com/newad.php?do=newad&cat=<?php urlencode($_POST['catselect']); ?>" target="_self">"
<div class="blocked">
<select name="catselect">
<option value="0">Please select a Category</option>
<optgroup label="Cars"></optgroup>
<option value="14" class="">BMW</option>
<option value="23" class="">Porsche</option>

这里的想法是获取选项值并将其用作使用newad.php创建新广告的类别。出于某种原因,在按下提交按钮之前,php没有将值提供给字符串,看起来该值为空。非常感谢有人提供一点见解!

3 个答案:

答案 0 :(得分:2)

PHP是一种服务器端脚本语言。 它在呈现页面之前评估scriptlet。 所以选择的价值可能就此没什么了。

每次选择新值时,请考虑使用javascript更改表单操作。

为下拉列表添加onchange事件

   <script type="text/javascript">
    <!--//
    change(val) {
        document.scriptform.action = "http://www.mysite.com/newad.php?do=newad&cat="+val;
    }
    //-->
    </script>

    <form name="scriptform" method="post" action=http://www.mysite.com/newad.php?do=newad&cat=" target="_self">"
    <div class="blocked">
    <select name="catselect" onChange="change(this.value)">
    <option value="0">Please select a Category</option>
    <optgroup label="Cars"></optgroup>
    <option value="14" class="">BMW</option>
    <option value="23" class="">Porsche</option>
    </select>
    </div>
    </form>

答案 1 :(得分:0)

你可以试试这段代码。

<html>
<head>
<script language="JavaScript" type="text/JavaScript">
    function optionsAlert(){
        var e = document.getElementById("catselect");
        var strUser = e.options[e.selectedIndex].value;
        alert(strUser);
        window.location.href="http://www.mysite.com/newad.php?do=newad&cat="+strUser;
    }
</script>
</head>

<form name="scriptform" method="post" >
<select name="catselect" id="catselect" onchange="optionsAlert()"/>
<option value="0">Please select a Category</option>
<optgroup label="Cars"></optgroup>
<option value="14" class="">BMW</option>
<option value="23" class="">Porsche</option>
</select>
</html>

答案 2 :(得分:0)

使用php

这是一种简单的方法
<?php
if(isset($_POST['catselect']))
{

    $path ="newad.php?do=newad&cat=".urlencode($_POST['catselect']);
    header("Location:".$path);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function change()
{
    document.scriptform.submit();
}
</script>
</head>

<body>
 <form method="post" name="scriptform">
    <div class="blocked">
    <select name="catselect" onChange="change(this.value)">
    <option value="0">Please select a Category</option>
    <optgroup label="Cars"></optgroup>
    <option value="14" class="">BMW</option>
    <option value="23" class="">Porsche</option>
    </select>
    </div>
    </form>
</body>
</html>