简体   繁体   English

HTML表单文本onChange事件刷新页面?

[英]HTML Form Text onChange event refreshes page?

 "use strict"; var SEED = ""; function seedSubmit() { var input_box = document.getElementById("seed-form"); SEED = input_box.elements[0].value; } 
 <form id="seed-form"> <p>Seed:</p> <input type="text" onchange="seedSubmit(); return false;"> <input type="button" onclick="seedSubmit()" value="Submit"> </form> 

Here's the HTML: 这是HTML:

<form id="seed-form">
    <p>Seed:</p>
    <input type="text" onchange="seedSubmit(); return false;">
    <input type="button" onclick="seedSubmit()" value="Submit">
</form>

Here's the JavaScript: 这是JavaScript:

"use strict";

var SEED = "";

function seedSubmit() {
    var input_box = document.getElementById("seed-form");
    SEED = input_box.elements[0].value;
}

I then use the SEED variable for some other stuff. 然后,我将SEED变量用于其他一些东西。 Basically you type into the box and press submit. 基本上,您在框中键入内容,然后按提交。 If the submit button is type="submit", it refreshes the page so it has to be a type="button" then it works fine. 如果提交按钮为type =“ submit”,则刷新页面,因此必须为type =“ button”,然后工作正常。 But I don't want a button at all I wanna type in the text and press enter. 但是我根本不想输入任何按钮,而是想要输入文本并按Enter。 But doing so refreshes the page. 但是这样做会刷新页面。 How do I prevent this? 我该如何预防? I did some googling and searching on this site and found a few posts but none of those solutions seemed to work, what am I doing wrong? 我在该网站上进行了谷歌搜索和搜索,发现了一些帖子,但这些解决方案似乎都不起作用,我在做什么错? People say try return false; 人们说try返回false; but that doesn't work for me. 但这对我不起作用。

You can add eventListener to "submit" and use the preventDefault method, for example: 您可以将eventListener添加到“提交”并使用preventDefault方法,例如:

 var SEED =""; var form = document.getElementById("seed-form"); form.addEventListener("submit", function(event){ event.preventDefault(); var input_box = document.getElementById("seed-form"); SEED = input_box.elements[0].value; console.log(SEED); }); 
 <form id="seed-form"> <p>Seed:</p> <input type="text" > <input type="submit" value="Submit"> </form> 

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

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