简体   繁体   中英

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.

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.

//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. 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".

This will prevent the page from reloading.

To prevent the page from reloading on hitting Enter, you can add this line to your form:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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