问题:有什么方法可以用JavaScript输入创建一个表单吗



我想在html页面上用JavaScript制作一个输入字段的表单。

我包含了完整的源代码&很抱歉,如果JS代码很大,我没有写它——这是一个开源项目。我真的希望能得到一些帮助。

我希望有一种方法可以将用JavaScript制作的输入字段包含到html表单中。

非常感谢!

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<base target="_parent">
<script>
if (window.parent !== window) {
try {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
} catch (error) {
// The above line can throw if we do not have access to the parent frame -- i.e. cross origin
}
}
</script>
<title>Storybook</title>

</head>
<body>
<div id="root"></div>
<div id="error-display"></div>
<script type="text/javascript" src="http://yourjavascript.com/2560291117/preview-0c18dfe69fe4ef4a04bd-bundle.js"></script></body>
</html>

function addInput() {
let input = document.createElement("input");
input.type = "text";
input.value = "Hello World!";
document.getElementById("form").appendChild(input);
}

该函数将其添加到id="0"的元素中;形式";,你是这个意思吗?

看完你的最后一条评论后,我想我已经明白你在找什么了?

(function(){

const form = document.createElement("form");
form.method = "POST";
form.action = "";

let fields = [
{name: "email", type: "email", label: "Email address*", id: "email_input"},
{name: "password", type:"password", label: "Password*", id: "password_input"},
{name: "rememberme", type:"checkbox", label: "Remember me?", id: "rememberme_input"}
];

fields.forEach(_ => {
if( typeof _.label != "undefined" ) {
const label = document.createElement("label");
label.setAttribute("for", `${typeof _.id == "string" ? _.id : ""}`);
label.innerHTML = _.label;
form.appendChild(label);
} 
form.appendChild(
createInput(
_.name,
_.type,
_.id
)
);
});


const button = document.createElement("button");
button.type = "submit";
button.innerHTML = "Submit";
form.appendChild(button);
document.body.appendChild(form);


function createInput(name, type="text", id="") {
const input = document.createElement("input");
input.type = type;
input.name = name;
input.id = id;
return input;
}

}());
form {
display: flex;
flex-direction: column;
justify-content: space-betwee;
max-width: 350px;
}
form input,
form button {
width: auto;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<base target="_parent">
<script>
if (window.parent !== window) {
try {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
} catch (error) {
// The above line can throw if we do not have access to the parent frame -- i.e. cross origin
}
}
</script>
<title>Storybook</title>

</head>
<body>
<div id="root"></div>
<div id="error-display"></div>

</body>
</html>

最新更新