Get number from user input and display in console with JavaScript

Getting user input numbers in JavaScript involves capturing values from HTML input elements and converting them to numeric types for processing. This tutorial shows how to get a number from user input and display it in the console.

HTML Structure

First, create the HTML form with an input field and button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Number Input</title>
</head>
<body>
    <div class="container">
        <h3>Number Input Example</h3>
        <form>
            <label for="inputNumber">Enter a number (1-100):</label>
            <input id="inputNumber" type="number" placeholder="Enter number" />
        </form>
        <button id="submitBtn">Submit Number</button>
        <p id="output"></p>
    </div>

    <script>
        function handleNumberInput() {
            const button = document.querySelector("#submitBtn");
            const input = document.querySelector("#inputNumber");
            const output = document.querySelector("#output");
            
            button.addEventListener("click", function() {
                const userInput = input.value;
                const numberValue = parseInt(userInput, 10);
                
                if (isNaN(numberValue)) {
                    output.textContent = "Please enter a valid number";
                    console.log("Invalid input:", userInput);
                } else {
                    output.textContent = `You entered: ${numberValue}`;
                    console.log("User entered number:", numberValue);
                }
            });
        }
        
        handleNumberInput();
    </script>
</body>
</html>

Key Methods for Number Input

Using parseInt()

The parseInt() method converts string input to an integer:

<script>
    function getNumberWithParseInt() {
        const input = document.querySelector("#numberInput");
        const button = document.querySelector("#parseIntBtn");
        
        button.addEventListener("click", function() {
            const userValue = input.value;
            const number = parseInt(userValue, 10);
            
            console.log("Original input:", userValue);
            console.log("Parsed integer:", number);
            console.log("Type:", typeof number);
        });
    }
</script>

Using Number() Constructor

The Number() constructor provides another way to convert input:

<script>
    function getNumberWithConstructor() {
        const input = document.querySelector("#numberInput");
        const button = document.querySelector("#numberBtn");
        
        button.addEventListener("click", function() {
            const userValue = input.value;
            const number = Number(userValue);
            
            if (Number.isNaN(number)) {
                console.log("Invalid number input");
            } else {
                console.log("Converted number:", number);
                console.log("Is integer:", Number.isInteger(number));
            }
        });
    }
</script>

Input Validation

Always validate user input to ensure it's a valid number:

<script>
    function validateNumberInput() {
        const input = document.querySelector("#validatedInput");
        const button = document.querySelector("#validateBtn");
        
        button.addEventListener("click", function() {
            const userInput = input.value.trim();
            
            // Check if input is empty
            if (userInput === "") {
                console.log("Error: No input provided");
                return;
            }
            
            // Convert to number
            const number = parseFloat(userInput);
            
            // Validate the number
            if (isNaN(number)) {
                console.log("Error: Invalid number format");
            } else if (number < 1 || number > 100) {
                console.log("Error: Number must be between 1 and 100");
            } else {
                console.log("Valid number entered:", number);
            }
        });
    }
</script>

Comparison of Methods

Method Handles Decimals Returns Best For
parseInt() No (truncates) Integer Whole numbers only
parseFloat() Yes Float Decimal numbers
Number() Yes Number General conversion

Complete Working Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Input Demo</title>
</head>
<body>
    <div>
        <h3>Enter a Number (1-100)</h3>
        <input id="userNumber" type="number" placeholder="Your number" />
        <button id="processBtn">Process Number</button>
        <p id="result"></p>
    </div>

    <script>
        function processUserNumber() {
            const input = document.querySelector("#userNumber");
            const button = document.querySelector("#processBtn");
            const result = document.querySelector("#result");
            
            button.addEventListener("click", function() {
                const inputValue = input.value;
                const number = parseInt(inputValue, 10);
                
                console.log("Processing user input...");
                console.log("Raw input:", inputValue);
                console.log("Parsed number:", number);
                
                if (isNaN(number)) {
                    result.textContent = "Please enter a valid number";
                    console.log("Validation failed: Not a number");
                } else {
                    result.textContent = `Number processed: ${number}`;
                    console.log("Success! Number processed:", number);
                }
            });
        }
        
        // Initialize the function
        processUserNumber();
    </script>
</body>
</html>

Expected Output

When you enter a number and click the button, the console will display:

Processing user input...
Raw input: 42
Parsed number: 42
Success! Number processed: 42

Conclusion

Getting numbers from user input requires capturing the input value with document.querySelector() and converting it using parseInt() or Number(). Always validate the input to ensure it's a valid number before processing.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements