Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HTML form values

People also ask

How do I get form values on submit?

To get form values on submit, we can pass in an event handler function into the onSubmit prop to get the inputted form values. We use the useState hook so that we can use the phone state as the value of the value prop.

How can we collect data from form in HTML?

The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs. The length of a URL is limited (about 3000 characters)

How do I get all inputs from a form?

To iterate through all the inputs in a form you can do this: $("form#formID :input"). each(function(){ var input = $(this); // This is the jquery object of the input, do what you will });


HTML:

<input type="text" name="name" id="uniqueID" value="value" />

JS:

var nameValue = document.getElementById("uniqueID").value;

If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:

JavaScript

const formData = new FormData(document.querySelector('form'))
for (var pair of formData.entries()) {
  // console.log(pair[0] + ': ' + pair[1]);
}

form-serialize (https://code.google.com/archive/p/form-serialize/)

serialize(document.forms[0]);

jQuery

$("form").serializeArray()

Here is an example from W3Schools:

function myFunction() {
    var elements = document.getElementById("myForm").elements;
    var obj ={};
    for(var i = 0 ; i < elements.length ; i++){
        var item = elements.item(i);
        obj[item.name] = item.value;
    }

    document.getElementById("demo").innerHTML = JSON.stringify(obj);
}

The demo can be found here.


document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
    if(form.id == "wanted_id") {
        form = document.forms[i];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);