Home >Web Front-end >JS Tutorial >How to Retrieve the Value of a Text Input Field Using JavaScript?

How to Retrieve the Value of a Text Input Field Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 17:12:221053browse

How to Retrieve the Value of a Text Input Field Using JavaScript?

How to Get Value of Text Input Field Using JavaScript

You can obtain the value of a text input field in JavaScript using these methods:

Method 1: getElementById

document.getElementById('input_id').value;

Method 2: getElementsByClassName

document.getElementsByClassName('class_name')[0].value;

Method 3: getElementsByTagName

document.getElementsByTagName('input')[0].value;

Method 4: getElementsByName

document.getElementsByName('input_name')[0].value;

Method 5: querySelector

By ID:

document.querySelector('#input_id').value;

By Class:

document.querySelector('.class_name').value;

By Tag Name:

document.querySelector('input').value;

Method 6: querySelectorAll

Similar to querySelector, but returns a static NodeList:

By ID:

document.querySelectorAll('#input_id')[0].value;

By Class:

document.querySelectorAll('.class_name')[0].value;

By Tag Name:

document.querySelectorAll('input')[0].value;

Example in Your Code

To get the value of the search text input field in your code, use:

const searchTxtValue = document.getElementById('searchTxt').value;

Browser Support

Browser Method 1 Method 2 Method 3 Method 4 Method 5/6
IE6 Y (Buggy) N Y Y (Buggy) N
IE7 Y (Buggy) N Y Y (Buggy) N
IE8 Y N Y Y (Buggy) Y
IE9 Y Y Y Y (Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N
FF3.5/FF3.6 Y Y Y Y Y
FF4b1 Y Y Y Y Y
GC4/GC5 Y Y Y Y Y
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y (Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y

The above is the detailed content of How to Retrieve the Value of a Text Input Field Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn