gpt4 book ai didi

Javascript/Typescript - 防止表单在提交时重置

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:41 25 4
gpt4 key购买 nike

我有一个简单的 typescript 类,想在提交时显示输入结果。尽管已经有人问过这个问题,但 event.preventDefault() 不起作用。也许你可以给我一些提示?

class LoginPanel {

public appDiv: HTMLElement = document.getElementById('app');

constructor() {
this.setForm();
let btn = document.getElementById('loginButton');
btn.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
}

public setForm(): void {
this.appDiv.innerHTML = `<form id="loginForm" class="form-signin mt-5">
<div class="text-center">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
</div>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
<button id="loginButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
`;
}

public submitForm(): void {
const elementFirst: HTMLElement = document.createElement('pre');
const elementSecond: HTMLElement = document.createElement('pre');

elementFirst.innerHTML = 'email: ' + document.getElementById('loginForm')[0].value;
document.getElementById('loginForm').appendChild(elementFirst);

elementSecond.innerHTML = 'password: ' + document.getElementById('loginForm')[1].value;
document.getElementById('loginForm').appendChild(elementSecond);
}

}

new LoginPanel();

最佳答案

提交表单时,您提交了所有值,而不仅仅是一个按钮。

因此,防止默认设置的正确位置是在表单元素本身内,而不是它的按钮。

constructor() {
this.setForm();
const form = document.getElementById('loginForm');
form.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
}

你可以看到这行得通 in this CodePen .

关于Javascript/Typescript - 防止表单在提交时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168909/

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