簡體   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