Getting HTML form values
HTML:
<input type="text" name="name" id="uniqueID" value="value" />
JS:
var nameValue = document.getElementById("uniqueID").value;
How do I get the value of text input field using JavaScript?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1
document.getElementById('textbox_id').value
to get the value of
desired box
For example
document.getElementById("searchTxt").value;
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0]
,
for the second one use [1]
, and so on...
Method 2
Usedocument.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
For example
document.getElementsByClassName("searchField")[0].value;
if this is the first textbox in your page.
Method 3
Use document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollection
For example
document.getElementsByTagName("input")[0].value;
, if this is the first textbox in your page.
Method 4
document.getElementsByName('name')[whole_number].value
which also >returns a live NodeList
For example
document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
Method 5
Use the powerful document.querySelector('selector').value
which uses a CSS selector to select the element
For example
document.querySelector('#searchTxt').value;
selected by iddocument.querySelector('.searchField').value;
selected by classdocument.querySelector('input').value;
selected by tagnamedocument.querySelector('[name="searchTxt"]').value;
selected by name
Method 6
document.querySelectorAll('selector')[whole_number].value
which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.
For example
document.querySelectorAll('#searchTxt')[0].value;
selected by iddocument.querySelectorAll('.searchField')[0].value;
selected by classdocument.querySelectorAll('input')[0].value;
selected by tagnamedocument.querySelectorAll('[name="searchTxt"]')[0].value;
selected by name
Support
Browser | Method1 | Method2 | Method3 | Method4 | Method5/6 |
---|---|---|---|---|---|
IE6 | Y(Buggy) | N | Y | Y(Buggy) | N |
IE7 | Y(Buggy) | N | Y | Y(Buggy) | N |
IE8 | Y | N | Y | Y(Buggy) | Y |
IE9 | Y | Y | Y | Y(Buggy) | Y |
IE10 | Y | Y | Y | Y | Y |
FF3.0 | Y | Y | Y | Y | N IE=Internet Explorer |
FF3.5/FF3.6 | Y | Y | Y | Y | Y FF=Mozilla Firefox |
FF4b1 | Y | Y | Y | Y | Y GC=Google Chrome |
GC4/GC5 | Y | Y | Y | Y | Y Y=YES,N=NO |
Safari4/Safari5 | Y | Y | Y | Y | Y |
Opera10.10/ | |||||
Opera10.53/ | Y | Y | Y | Y(Buggy) | Y |
Opera10.60 | |||||
Opera 12 | Y | Y | Y | Y | Y |
How can I get all a form's values that would be submitted without submitting
The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.
var queryString = $('#myFormId').formSerialize();
From http://malsup.com/jquery/form
Or using straight jquery:
var queryString = $('#myFormId').serialize();
Getting all form values by JavaScript
Here is a working fiddle in vanilla JavaScript, but you need to add a serialize utility function. This works exactly like $('form').serialize()
in jQuery.
JavaScript:
var data;
function serialize(form) {
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
}
break;
}
break;
case 'file':
break;
case 'TEXTAREA':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
}
break;
}
}
data = q.join("&");
}
And change your form onchange
to
<form onchange="serialize(this)">
I tested it and am getting "size=small&status=0"
in the console.
Getting HTML form values with JavaScript and saving them into JSON key and value pairs
I believe there was an issue with how you were passing your event into your function and trying to call preventDefault()
. I put your function directly on the event listener method with async
keyword.
As previously mentioned, document.querySelector()
uses CSS selectors unlike document.getElementById()
. In your case I would stick with getting the input elements by their ID.
Like Paul said in his answer, you need a JavaScript object for JSON.stringify() to work properly.
document.getElementById("save").addEventListener('click', async function(e) {
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = {
username: userData,
account: acctData
}; // create JS object
console.log(JSON.stringify(formData));
});
<form id="form" method="POST" action="#">
<input type="text" id="username" name="username" placeholder="Enter Username">
<input type="text" id="account" name="account" placeholder="Enter Account">
<button type="submit" id="save">Save</button>
</form>
Get form values through JavaScript
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
How to get values from posted html form using javascript
You can't use POST
method because with a plain HTML page you do not have HTTP headers but HTML page code itself and URL (with query string).
What you can do is to use GET
instead of POST
then parse query string to extract them:
<form name ="form1" id ="form1" method ="GET" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
Then in your form2.html
you can use this function (from this post on SO) to parse query string:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Now (let me use jQuery) you can access them with this:
<form ...>
<input id ="sentFromForm1" type ="hidden" value =""/>
</form>
</script>
$("#sentFromForm1").val(getParameterByName("sendToForm2"));
</script>
Related Topics
Show Hide Divs on Click in HTML and CSS Without Jquery
Passing Form Data to Another HTML Page
How to Detect Which One of the Defined Font Was Used in a Web Page
How to Refer to JavaScript Variables Across Webpages in a Browser Session
Set Active Tab Style With Angularjs
Turn a Number into Star Rating Display Using Jquery and Css
Should CSS Always Precede JavaScript
Detect Ipad/Iphone Webview Via JavaScript
Xmlhttprequest Cannot Load Xxx No 'Access-Control-Allow-Origin' Header
What Does This Symbol Mean in JavaScript
How to Display JavaScript Variables in a HTML Page Without Document.Write
Onclick Open Window and Specific Size
Conditionally Load JavaScript File
Textarea That Can Do Syntax Highlighting on the Fly
Html5 Canvas Camera/Viewport - How to Actually Do It
How to Set Font Size Based on Container Size
Fixed Positioning in Mobile Safari
How to Correctly Detect Orientation Change Using Phonegap on Ios