0

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.

2
  • There's no best method for this, it all depends on your use case and the libraries you use. For example, with jquery its a one liner - $("form").serializeArray() and you get all the fields and values in a single array Commented Mar 28, 2020 at 9:33
  • thank you, yes, the best will be depended on the use cases. I am researching easiest to understand. Commented Mar 28, 2020 at 15:05

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, document.querySelector() returns the first form (or matching element).
If you have several forms on the page and want to access them using this approach you can add either id or class for each form and use document.querySelector('#form-id') or document.querySelector('.form-class') respectively.
1
let searchTxt= document.forms["F"]["searchTxt"].value;

2 Comments

What does this answer add to address OP's question?
@dhamkith , thank you. Do you know which is safer or same between document.forms["F"]["searchTxt"] and document.forms["F"].elements["searchTxt"] ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.