gpt4 book ai didi

javascript - 如何通过控制台记录整个 HTML 表单?

转载 作者:行者123 更新时间:2023-11-28 17:10:39 25 4
gpt4 key购买 nike

我正在尝试控制台记录整个表单,但 JavaScript 代码变得太长。谁能帮助我如何遵循 DRY(不要重复自己),因为我在脚本标签中重复了很多代码

<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName < /label> < input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input onclick="myFunction()" id="button" type="submit">
</li> </ul>
</form>

这是我的脚本标签。我想遵循 DRY 规则。我尝试将值保存到每个单独的变量中。

    <script>
var nameInput = document.getElementById('simple-input1');

document.querySelector('form.form').addEventListener('submit', function(e) {

//prevent the normal submission of the form
e.preventDefault();

console.log("Username: " + nameInput.value);
});

var nameInput1 = document.getElementById('simple-input2');

document.querySelector('form.form').addEventListener('submit', function (e) {

//prevent the normal submission of the form
e.preventDefault();

console.log("Password: " + nameInput1.value);
});


</script>

最佳答案

您可以使用document.querySelector('form.form').elements获取表单元素

document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
let x = document.querySelector('form.form').elements;
console.log("Username: ", x['userid'].value);
console.log("Password: ", x['pwd'].value);
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName</label>
<input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;">
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;">
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>

关于javascript - 如何通过控制台记录整个 HTML 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com