Open In App

How to Get Value of Input in TypeScript ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you’re handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential.

The below approaches can be utilized to get input value in TypeScript:

Using document.getElementById

This approach involves using Vanilla JavaScript to access input elements by their IDs and then retrieving their values using the value property.

Syntax:

const inputElement = document.
getElementById("inputId") as
HTMLInputElement;
const value: retrievingValueType = inputElement.value;

Example: The below example retrieves the entered input value in Vanilla JavaScript and displays it on the screen.

HTML
<!-- index.html file-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Username Input
    </title>
</head>

<body>
    <input type="text" id="username" 
        placeholder="Enter your username" />
    <button id="submitBtn">
        Submit
    </button>
    <p id="result"></p>
</body>

</html>
JavaScript
//index.ts file

let usernameInput: HTMLInputElement = document.
    getElementById('username') as HTMLInputElement;
let result: HTMLParagraphElement = document.
    getElementById('result') as HTMLParagraphElement;
let username: string;

document.getElementById('submitBtn').
    addEventListener('click', function () {
        username = usernameInput.value;
        if (username) {
            result.textContent =
                'Entered Username: ' + username;
        }
        else {
            result.textContent =
                'Input field can not be empty';
        }
    });

Output:

fosiGIF

Retrieving value in React

React provides controlled components where input values are managed by state, facilitating easy access to input values.

Syntax:

const [username, setUsername] = useState<string>('');
<input type="text" value={username}
onChange={(e) => setUsername(e.target.value)} />

Example: The below code will explain how you can get the value of input element in ReactJS.

JavaScript
import React, { useState } from 'react';

const App: React.FC = () => {
    const [username, setUsername] = useState<string>('');

    const handleInputChange = 
        (e: React.ChangeEvent<HTMLInputElement>) => {
            setUsername(e.target.value);
        };

        return (
        <div>
            <input type="text" value={username} 
                onChange={handleInputChange} 
                placeholder="Enter your username" />
            <p>Username: {username}</p>
        </div>
    );
};

export default App;

Output:

fosiGIF



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads