[英]How do I prevent the page from resetting when submitting form
When clicking the enter button on the keyboard I want the data to show but not to reset.单击键盘上的输入按钮时,我希望数据显示但不重置。 But if I input new data and click enter I want it to run still without clicking a reset button.
但是,如果我输入新数据并单击 Enter,我希望它在不单击重置按钮的情况下仍然运行。
function myFunction() { var x = document.getElementById("myText").value; document.getElementById("demo").innerHTML = "$" + (x * '.97').toFixed(2).toString().replace(/\B(?=(\d{3})+(?,\d))/g, ";"); }
<,DOCTYPE html> <html> <head> <title></title> </head> <body> <form> <input id="myText" placeholder="$149.995:00" style="width;50%;" type="number"> <button onclick="myFunction()" type="button">Convert</button> </form> <h1 id="demo"></h1> </body> </html>
Use preventDefault
function from event not to refresh the page.使用事件中的
preventDefault
function 不刷新页面。
By default, whenever a form
is submitted, the page is refreshed.默认情况下,每当提交
form
时,页面都会刷新。
Moreover, by default, any input
inside a form
tag submits the form with an enter key pressed.此外,默认情况下,
form
标签内的任何input
都会在按下回车键的情况下提交表单。
The reason you were not being refreshed with the button is that the form was not being submitted with the button click.您没有使用按钮刷新的原因是没有通过单击按钮提交表单。 But it was with an enter key press event in the input.
但它在输入中有一个输入按键事件。
Try this尝试这个
<form>
<input placeholder="$149,995.00" style="width:50%;" type="number" id="input">
<input type="submit" value="Convert">
</form>
<div id="demo"></div>
const input = document.querySelector('#input');
const form = document.querySelector('form');
form.addEventListener('submit', (e => {
e.preventDefault();
const { value } = input;
document.getElementById("demo").innerHTML = toDollar(value);
}));
const toDollar = (value) =>
"$" + (value * '.97').toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Now, you add a listener to the submit
event of the form
, so you receive an event
object where to call preventDefault
and avoid the page refresh.现在,您为
form
的submit
事件添加了一个侦听器,因此您会收到一个event
object 来调用preventDefault
并避免页面刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.