How to get value from textfield with javascript

Ask a question+

I currently have a form that the user enters data into, however I need to in real time detect what they entered to see if it matches certain things.

Does anyone know how to get form data with javascript? Ideally drop down and text field at least.

Lian 335
add comment

1 Answer


I realize that you asked this a month ago, but hopefully you didn’t need this earlier… here is the solution to your two problems:

Accessing inputs data in real-time:
For accessing the data in realtime, you can use an eventListener function called oninput. You use it like this:

<input name="input_name" id="input_id" type="text" oninput="ValidateInput(this)">

Then you use JavaScript to check it:

function ValidateInput(form_element) {
    var elements_value = form_element.value();
    // Code to check value here

Because we are passing the element into the function you can access the value and change it, or use it to access another element around it to show an error or something.

The oninput built-in function is one of the only eventListeners that is a realtime function. It is called the very millisecond that the data in the form element is changed.

Accessing form data:
W3Schools has a page about the DOM form object. You can view that page here.

So if you give your form an id, you can access it like this:

<form id="my_form">
    <!-- form elements here -->
var my_form = document.getElementById("my_form");

With the form element accesed, you can now view all form elements by doing something like this:

var my_form = document.getElementById("my_form");

for (var i = 0; i < my_form.length; i++) {
    // You can access each form element like this:
    /* Note:
     * This gets more than just the <input>, <select>, and <textarea>
     * it also accesses the <fieldset>, <label>, <button>, <datalist>,
     * and pretty much every element contained inside the form element.

To access just the form elements that you want, just give each one a unique name attribute (except for the radio buttons), and then use this instead of what I shared above (two code blocks above):

var my_form = document.getElementById("my_form").filter((form_element) => {return form_element.name.length > 0;});
/* If that doesn't actually work, let me know, I wasn't able to test it, and I'm not to skilled with
   those special Array methods, and so I'm not totally sure that it is the correct way to do it. */

If you need any additional help with this, please let me know! I’m not advanced with HTML forms and accessing them with JavaScript, but I have had lots of practice, so I will most likely be able to help!

Batman 210
add comment

Your Answer