繁体   English   中英

当我在数组中推送一个对象时,它仍然是空的

[英]When I push an object in array it remains empty

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

 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函数。 这会修改您的数组。

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

这(可能)是用户已经在查看的页面。 虽然它是它的新副本,但它不包含旧版本的数组。


你可以return false; onsubmit函数的末尾,以防止表单提交。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM