Reputation: 41
I want to access input field value as simple as possible from JavaScript.
<form name="F">
<input name="searchTxt" type="text" id="searchTxt">
</form>
I can access the value with following method (tested on Firefox debugger):
document.F.searchTxt.value
But I found this method is a dialect from Internet Explorer (and works on most browsers for compatibility), and it is obsoleted on W3C DOM. (reference: Using the W3C DOM - Archive of obsolete content | MDN )
Another way I found is using forms
and elements
attributes with its child's name:
document.forms.F.elements.searchTxt.value
I like this method and I feel it is simple because it doesn't require any parentheses or quotes but only dots in the statement. (reference: Obtaining References to Forms and Form Elements in JavaScript - Dynamic Web Coding )
I think the secret of this method is the form
has its name
(instead of or additional to id
), so it can be accessed by its simple name.
Please tell me more simple, more stable or the best method to access the field values.
Upvotes: 0
Views: 2162
Reputation: 800
You can use document.querySelector
to access the form's DOM element and it has all the properties that you need:
const form = document.querySelector('form');
console.log(form.elements.searchTxt.value);
Upvotes: 1