JSFiddle - React, Tailwind, and code Playground
by sp182
HTML
<input type="text" id="txtName" placeholder="Enter Your Name" />
<input type="text" id="intAge" placeholder="Enter Your Age" />
<input type="text" id="txtColour" placeholder="Enter Your Favourite Colour" />
<input type="submit" value="Save" id="btnSave" />
<input type="submit" value="Get Data" id="btnGet" />
JavaScript
/////
///Save Data Function
/////
function saveData(){
//Our text field data
var txtName = $('#txtName').val();
var intAge = $('#intAge').val();
var txtColour = $('#txtColour').val();
//Test to see if the browser supports localStorage
if(localStorage){
//Set the name, age and colour items
localStorage.setItem('name' , txtName);
localStorage.setItem('age' , intAge);
localStorage.setItem('colour' , txtColour);
}
//Alert the user to upgrade their browser
else {
alert('Local storage not supported. Please get a proper browser');
}
}
/////
///Get Data Function
/////
function getData(){
//Create an empty results string
var strResults = '';
//Test to see if the browser supports localStorage
if(localStorage){
//Declare the item values as variables
var txtName = localStorage.getItem('name');
var intAge = localStorage.getItem('age');
var txtColour = localStorage.getItem('colour');
//Build the results into the results string
strResults += 'Hi There '
+ txtName
+ ' You are '
+ intAge
+ ' years old'
+ ' and your favourite colour is '
+ txtColour
+ '';
//Append the body with the results
$('body').append(strResults);
}
//Alert the user to upgrade their browser
else {
alert('Local storage not supported. Please get a proper browser');
}
}
/////
///Document Ready
/////
$(document).ready(function(){
//Bind events to the buttons to fire off the functions
$('#btnSave').bind('click' , saveData);
$('#btnGet').bind('click' , getData);
});