表单按钮在JS中动态添加

时间:2015-12-29 18:48:14

标签: javascript forms button listener

我尝试在JavaScript中动态添加表单,但是当我点击提交按钮时没有任何反应。我知道这是因为按钮没有监听器,但是我不知道我必须在监听器中添加什么才能获得正常的发送按钮行为。

这里有一些我的代码

document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("partTwo").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>T&eacute;l&eacute;charger le rapport</button>";
document.getElementById("partTwo").innerHTML += "</form>";

我希望听众能够将表单发送到我的client.process.php

我知道这是一个初学者的问题,但任何帮助都会受到赞赏。 感谢

3 个答案:

答案 0 :(得分:2)

<强> Working fiddle

您应该在form内添加输入,而不是在div partTwo中添加,因此您的代码应该是:

document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("download_report").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>T&eacute;l&eacute;charger le rapport</button>";

希望这有帮助。

答案 1 :(得分:1)

问题是<form>标记是自动关闭的。 innerHTML返回格式正确的HTML。见this question

答案 2 :(得分:0)

您应该考虑使用createElement而不是innerHTML,请参阅2946656

以下是如何创建表单并将其附加到页面的基本示例:

var form = document.createElement("form");
form.setAttribute('action', 'contact.php');
form.setAttribute('method', 'POST');

var inputField = document.createElement("input");
inputField.setAttribute('value', 'example');
form.appendChild(inputField);

document.body.appendChild(form);

相关问题