Home >Web Front-end >JS Tutorial >How Can I Get the Value of a Text Input Field in JavaScript?
How to Obtain Text Input Field Value in JavaScript
To acquire the input value from a text field without using an HTML form, several methods can be employed in JavaScript.
Method 1 (getElementById)
document.getElementById('searchTxt').value;
Method 2 (getElementsByClassName)
document.getElementsByClassName('searchField')[0].value;
Method 3 (getElementsByTagName)
document.getElementsByTagName('input')[0].value;
Method 4 (getElementsByName)
document.getElementsByName('searchTxt')[0].value;
Method 5/6 (querySelector/querySelectorAll)
// Use unique identifier, class, tag, or attribute selection document.querySelector('input[type="text"]').value;
Note: Methods 2, 3, 4, and 6 return collections of elements. Use numerical indices to access specific elements.
Browser Support
The following table outlines browser support for these methods:
Browser | Method 1 | Method 2 | Method 3 | Method 4 | Method 5/6 |
---|---|---|---|---|---|
IE6 | Buggy | No | Yes | Buggy | No |
IE7 | Buggy | No | Yes | Buggy | No |
IE8 | Yes | No | Yes | Buggy | Yes |
IE9 | Yes | Yes | Yes | Buggy | Yes |
IE10 | Yes | Yes | Yes | Yes | Yes |
FF 3.0 | Yes | Yes | Yes | Yes | No |
FF 3.5/3.6 | Yes | Yes | Yes | Yes | Yes |
FF 4b1 | Yes | Yes | Yes | Yes | Yes |
GC4/GC5 | Yes | Yes | Yes | Yes | Yes |
Safari 4/5 | Yes | Yes | Yes | Yes | Yes |
Opera 10.10/ | No | No | No | No | No |
Opera 10.53/ | Yes | Yes | Yes | Buggy | Yes |
Opera 10.60 | No | No | No | No | No |
Opera 12 | Yes | Yes | Yes | Yes | Yes |
The above is the detailed content of How Can I Get the Value of a Text Input Field in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!