简体   繁体   English

需要帮助获取和使用 JavaScript 中的 HTML 形式的用户输入

[英]Need help getting and using user input with HTML form in JavaScript

I need help in asking the user for input and saving the input into a variable to do things with it.我需要帮助来询问用户输入并将输入保存到变量中以使用它。 I'm trying to find a method that's similar to how Java uses Scanner to ask for user input.我试图找到一种类似于 Java 使用 Scanner 来询问用户输入的方法。

I want to use an input box for the user to enter in their input.我想使用一个输入框让用户输入他们的输入。 Simply capturing the value of the input is not working for me since the entire page refreshes as soon as the form gets submitted.简单地捕获输入的值对我不起作用,因为一旦提交表单,整个页面就会刷新。 I'm also not sure how I can use the variable containing the user input outside of the function scope as it becomes undefined when trying to use it outside of the function.我也不确定如何在 function scope 之外使用包含用户输入的变量,因为当尝试在 ZC1C425268E68385D1AB5074C17A94F1 之外使用它时它变得未定义。

//html file------------------------------------------
<form id="form1">
    <label for="cardNum">MasterCard Number:</label>
    <input id="cardNum" name="num" type="text" placeholder="Enter a 16-digit number">
    <button onclick="outputnum()" id="submit">Submit</button>
</form>
<h1>Welcome</h1>

//JS FILE--------------------------------------------

function outputnum(){
    var number = document.getElementById("cardNum").value;
    document.querySelector("h1").innerHTML = number;
}

I am not trying to use a prompt/alert function to get the user input.我不想使用提示/警报 function 来获取用户输入。 I need to get it from an input box.我需要从输入框中获取它。

If you don't need the form to submit, change the button to button type by adding type="button" after id="submit".如果您不需要提交表单,请通过在 id="submit" 后添加type="button"将按钮更改为按钮类型。

This will prevent the page from reloading.这将防止页面重新加载。

To prevent the page from reloading on hitting Enter, you can add this line to your form:为了防止页面在按 Enter 时重新加载,您可以将此行添加到表单中:

<Input type="submit" hidden disabled>

Below is a basic example that will prevent the default action of the submit.下面是一个基本示例,它将阻止提交的默认操作。 Let me know if you have any questions:)如果您有任何问题,请告诉我:)

 var submitEl = document.getElementById('submitting'); var inputValueEl = document.getElementById('cardNum'); // Add a event listener to the submit button and prevent the form submit submitEl.addEventListener('click', function(event) { // preventDefault() will prevent the submit, which will cause the page to refresh event.preventDefault(); // validate credit card number validateCard(inputValueEl.value); }); function validateCard(num) { // Do stuff with the num value here. alert(num); }
 <form id="form1"> <label for="cardNum">MasterCard Number:</label> <input id="cardNum" name="num" type="text" placeholder="Enter a 16-digit number"> <button id="submitting" type="submit">Submit</button> </form> <h1>Welcome</h1>

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

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