我正在使用JSON格式将用户输入的详细信息本地存储在表单中。不使用JQuery或其他库。该站点将检查是否需要空字段,或者将用户输入存储为值对,但不会同时执行这两个操作。 onsubmit确保字段不为空,但不存储输入,而onclick则相反。还会显示我设置的必填属性不起作用 是否可以将它们合并在一起或同时工作?
我的Javascript代码:
//Array storing user input
let players = [];
const users = (ev)=>{
ev.preventDefault(); //to stop the form submitting
let player = {
username: document.getElementById('username').value,
password: document.getElementById('password').value,
email: document.getElementById('email').value,
country: document.getElementById('country').value
}
players.push(player);
document.querySelector('form').reset();
//for display purposes only
console.warn('added' , {players} );
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('sign').addEventListener('submit', users);//Checks validation
document.getElementById('sign').addEventListener('click', users);//Stores to JSON array players
});
相关的PHP:
//This is the username and password field
function formFill ($newOrReturn) {
echo '<form class="box" method="#" id="btn" >';
echo '<h1>' .$newOrReturn. '</h1>';
echo '<input type="text" name="" placeholder="Username" id="username" required>';
echo '<input type="password" name="" placeholder="Password" id="password" required>';
}
相关的HTML:
<input type="email" name="" placeholder="Email" id="email" required>
<input type="text" name="" placeholder="Country" id="country" required>
<input type="submit" name="" value="Sign Up" id="sign">
</form>