0

我有一个 HTML 表单,在使用一些 javascript 更改操作后提交。两个不同的按钮可以进行提交。

有趣的是,我试图调试它并在更改操作后和提交表单之前插入警报。提交表单时不会显示警报。为了确保它实际上在执行 javascript,我在更改操作之前添加了一个警报。该警报显示;更改操作后的警报不会。

<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>

<script type="text/javascript">
function SubmitForm(target){
    alert("Action 1: " + document.FormSelect.action);
    if (target=="class") {
        document.FormSelect.action = "ClassAction.php";
    } else {
        document.FormSelect.action = "StudentAction.php";
    }
    alert("Action 2: " + document.FormSelect.action);
 // document.FormSelect.submit();
    }
</script>

这是预期的事件顺序吗?

4

4 回答 4

1

放置在表单元素内的任何按钮都会导致提交操作。为了防止这种情况,您可以将 type="button" 添加到按钮元素,或者让您提交回调返回 false;

<button type="button" onclick="SubmitForm('class')">Submit</button

http://jsfiddle.net/yD2Uu/

于 2013-04-30T20:41:44.860 回答
0

As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.

<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>

It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)

function SubmitForm(button){
  button.form.action = button.formaction;
}
于 2013-04-30T21:02:01.700 回答
0

感谢 Yauhen Vasileusky 的示例,我开始在第一个和第二个警报之间删除代码,发现问题似乎是以下 IF 语句:

if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}

当我删除它时,会显示两个警报。所以我的问题的答案是更改操作不会提交表单;我的代码中的其他一些错误使它看起来好像是这种情况。

于 2013-05-01T20:24:50.037 回答
0

更好的解决方案是为每个按钮命名并提交给 Action.php 并让服务器获取命名按钮的值

$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning

当你有

<form method="post" action="Actions.php">
  <input type="submit" name="student" value="John Doe" />
  <input type="submit" name="student" value="Jane Doe" />
  <input type="submit" name="student" value="Whatever Doe" />
</form>

否则,如果你必须

尝试这个

<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>

<script type="text/javascript">
var actions = {
  "class":"ClassAction.php",
  "student":"StudentAction.php"
}

function SubmitForm(button){
  button.form.action = actions[button.value];
  button.form.submit();
}
</script>
于 2013-04-30T20:35:29.077 回答