You can use FormData to get form data in JavaScript. The FormData
interface allows you to construct a set of key/value pairs representing form fields and their values in 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()
Simple way using onclick or JavaScript addEventListener submit.
HTML:
<input type="text" name="name" id="uniqueID" value="value" />
JS:
var nameValue = document.getElementById("uniqueID").value;
Get form data in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<form name="valform" action="" method="POST">
Credit Card Validation:
<input type="text" id="cctextboxid" name="cctextbox">
<br/>
Card Type:
<select name="cardtype" id="cardtypeid">
<option value="visa">Visa</option>
<option value="mastercard">MasterCard</option>
<option value="discover">Discover</option>
<option value="amex">Amex</option>
<option value="diners">Diners Club</option>
</select><br/>
<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />
<script>
const formData = new FormData(document.querySelector('form'))
for (var pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1]);
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this Js form topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version