Read and Write HTML Form Data
EasyProgramming.net tutorial on reading and writing form element data
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 18 - Reading and Writing Form Element Values -->
<p>
Welcome to the 18th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We did a lot of reading and writing DOM elements, but they require things to be hard coded or require some programmatic handling in order to allow you to do something with them.
</p>
<p>
In the real world, forms are the preferred way for user input. And with a little bit of JavaScript, you can even output values to form elements.
</p>
<p>
Let's take a look!
</p>
<label for="name">Name: </label><input id="name" type="text" /><br /><br />
<label for="name">City: </label><input id="city" type="text" /><br /><br />
<button id="submit">Submit</button>
<button id="capitalize">Capitalize Everything!</button>
<button id="clear">Clear</button>
<p>
Your Name is <span id="outputName">____</span>. The city in which you live is <span id="outputCity">____</span>.
</p>
CSS
#outputName, #outputCity{
color: red;
}
JavaScript
var submit = document.getElementById("submit");
var capitalize = document.getElementById("capitalize");
var clear = document.getElementById("clear");
submit.onclick = function(){
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
document.getElementById("outputName").innerText = name;
document.getElementById("outputCity").innerText = city;
}
capitalize.onclick = function(){
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
document.getElementById("name").value = name.toUpperCase();
document.getElementById("city").value = city.toUpperCase();
}
clear.onclick = function(){
document.getElementById("name").value = "";
document.getElementById("city").value = "";
}