我有一个联系表单,其中包含一个带有选项的下拉列表,现在我需要根据用户从下拉列表中点击的选项," Action"在联系表单上进行更改,这样我可以根据选项分配不同的PHP文件。我知道我想要的是我只是很难对其进行编码以使其正常工作。我将在下面提供html表单和PHP。
<div id="form123">
<form id="my-form" action="sitephp.php" method="post">
<table width="343" border="0" align="center">
<tbody>
<tr>
&#13;
<select name="Machine" required id="Machine" onChange="changeSelectValue();">
<option selected="selected"></option>
<option id="machine 1" value="sitephp1.php">machine 1</option>
<option value="sitephp2.php">machine 2</option>
<option id="machine 3" value="sitephp3.php">machine 3 </option>
</select>
&#13;
<script type="text/javascript" >
function changeSelectValue() {
var myForm = document.querySelector('#my-form');
var selectValue = document.querySelector('#Machine').value;
var actionFile = '';
switch (selectValue) {
case 'machine 1':
actionFile = 'sitephp1.php';
break;
case 'machine 2':
actionFile = 'sitephp2.php';
break;
case 'machine 3':
actionFile = 'sitephp3.php';
break;
default:
break;
}
myForm.setAttribute('action', actionFile);
}
</script>
&#13;
<?php
$email1=$_POST['Email1'];
$email2=$_POST['Email2'];
$from=$_POST['Email1'];
$email='YOUR EMAIL HERE';
$subject=" Request ";
$message=$_POST['Box'];
$machine=$_POST['Machine'];
$name=$_POST['Name'];
$phone=$_POST['Phone'];
$number=$_POST['Number'];
$message="Name: ".$name."\r\n"."Phone: ".$phone."\r\n"."Email: " .$from ."\r\n"."Machine: ".$machine."\r\n"."Problem: ".$message ;
if ($number !=10) {
die("You are not a human! or your answer was incorrect!, Please go back and try again.");
}
if(!filter_var($email1, FILTER_VALIDATE_EMAIL)) {
die("Invalid email ($email1)");
}
if ($email1 == $email2) {
mail ($email, $subject, $message, "from:".$from);
echo 'Thanks You for the Maintenance Request! We will Contact you shortly. ';
}
else {
echo "This ($email2) email address is different from ($email1).\n";
}
?>
&#13;
答案 0 :(得分:1)
将函数bind添加到select的onchange中,如下所示:
<select name="Select" required id="Select" onchange="changeSelectValue();">
在表单中添加ID:
<form id="my-form" action="sitephp.php" method="post">
使用以下JS代码根据所选值更改操作属性:
function changeSelectValue() {
var myForm = document.querySelector('#my-form');
var selectValue = document.querySelector('#Select').value;
if (selectValue.length > 0) {
myForm.setAttribute('action', selectValue);
}
}
只需将file1.php
,file2.php
和file3.php
更改为您的文件即可。
如果您没有附加到页面的JS文件,请将上述JS代码包含在<script type="text/javascript"></script>
中,并将其放在正文结束标记之前的页面末尾。
P.S。现在您更改了代码,将文件名直接调用到选项的值中。通过这种方式,您不再需要切换案例,您可以直接使用select的值作为要使用的表单的action属性。
答案 1 :(得分:1)
最好有一个主*.php
脚本,您可以根据用户的输入选择更进一步的事件,例如:
switch ( $_POST['Machine'] ) {
case 0:
include 'script1.php';
break;
case 1:
include 'script2.php';
break;
case 2:
include 'script3.php';
break;
}