gpt4 book ai didi

javascript - 当我将一个对象插入数组时,它仍然是空的

转载 作者:行者123 更新时间:2023-11-30 11:21:37 25 4
gpt4 key购买 nike

每当提交我的表单时,什么都没有发生,当我检查我的数组时控制台它仍然是空的。为了定位输入值,我需要将它放在一个函数中,我也在函数中使用了 return 但没有任何反应。实际上,我希望在对象中收集用户数据,并在我单击提交按钮时将其推送到数组中...

var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password:  inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Gender: inputsarray[6, 7].checked,
Purpose: inputsarray[8, 9, 10].checked
};
array.push(users);
}
<div>
<center>
<form method="post" onsubmit="subm();">
<label for="fname">First Name:</label>&emsp;
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label>&emsp;
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label>&emsp;
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>&emsp;&ensp;&nbsp;
<input type="text" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>&emsp;&emsp;&nbsp;
<input type="date" id="dob" />
<br/>
<label>Age:</label>&emsp;&emsp;&emsp;&emsp;&emsp;
<input type="text" id="age" />
<br/>
<span>Gender:</span>&emsp;&emsp;&emsp;&emsp;&ensp;
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>

最佳答案

当您按下提交按钮时,您就开始了表单提交过程。

首先运行 onsubmit 函数。这会修改您的数组。

然后表单提交并加载新页面。

这(大概)是用户已经在查看的同一页面。不过,这是它的新副本,因此它不包含旧版本中的数组。


您可以在 onsubmit 函数的末尾return false; 来阻止表单提交。

现代代码会使用 addEventListener (大约二十年前介绍)并调用事件对象的 preventDefault 方法。

document.querySelector("form").addEventListener("submit", subm);
function subm(event) {
event.preventDefault();
// etc
}

关于javascript - 当我将一个对象插入数组时,它仍然是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630477/

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