How can I load a value using html5 local storage - javascript

I want to get my input also as an outup in an form table. I copied the code beneath because I only want to know how to get my output.
I think that I have to change this
<input type="button" value="load" onclick="load_local();"/
so when I click on a button I get the value in a box like a form
<!DOCTYPE HTML>
<html>
<head>
<TITLE>HTML5 local storage tester (testbed)</TITLE>
</head>
<body>
<div id="output_area"
style="position:relative;width:100%;height:200px;overflow:auto;
border: dotted 1px #ff0000;">
</div>
<div>
<input id="local_storage_key" type="text" />
<input id="local_storage_value" type="text" />
</div>
<div>
<input type="button" value="load" onclick="load_local();"/>
<input type="button" value="store" onclick="store_local();"/>
</div>
<script id="this_page_js" type="text/javascript">
/* store some string data to local storage
This is using some text input elements on the page
for input.*/
function store_local(domid_prefix){
var keyinput = document.getElementById('local_storage_key').value;
var valinput = document.getElementById('local_storage_value').value;
try{
if(typeof(window.localStorage) != 'undefined'){
window.localStorage.setItem(keyinput,valinput);
}
else{
throw "window.localStorage, not defined";
}
}
catch(err){
output_str("store_local,error," + err);
}
}
/* load some string data from local storage
This is using some text input elements on the page
for the key name input and value output.*/
function load_local(domid_prefix){
var keyinput = document.getElementById('local_storage_key').value;
var valoutput = document.getElementById('local_storage_value');
try {
if(typeof(window.localStorage) != 'undefined') {
valoutput.value = window.localStorage.getItem(keyinput);
}
else {
throw "window.localStorage, not defined";
}
}
catch(err) {
output_str("store_local,error," + err);
}
}
/* function to print to the debug area */
function output_str(str){
var da = document.getElementById("output_area");
da.innerHTML += str + "<br/>";
da.scrollTop = da.scrollHeight;
}
</script>
</body>
</html>
thanks for answering.

<html>
<head>
<title>Test</title>
</head>
<body>
<input type="text" id="txt1" /><br/>
<input type="text" id="txt2" /><br/>
<input type="text" id="txt3" /><br/>
<input type="text" id="txt4" /><br/>
<input type="text" id="txt5" /><br/>
<input type="text" id="txt6" /><br/>
<input type="text" id="txt7" /><br/>
<input type="text" id="txt8" /><br/>
<input type="button" id="btn" value="Save" onclick="javascript: return save();"/>
<div id="output"></div>
<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript">
function save()
{
var arr =new Array();
var obj1 = parseInt(document.getElementById("txt1").value);
var obj2 = parseInt(document.getElementById("txt2").value);
var obj3 = parseInt(document.getElementById("txt3").value);
var obj4 = parseInt(document.getElementById("txt4").value);
var obj5 = parseInt(document.getElementById("txt5").value);
var obj6 = parseInt(document.getElementById("txt6").value);
var obj7 = parseInt(document.getElementById("txt7").value);
var obj8 = parseInt(document.getElementById("txt8").value);
arr.push(obj1);
arr.push(obj2);
arr.push(obj3);
arr.push(obj4);
arr.push(obj5);
arr.push(obj6);
arr.push(obj7);
arr.push(obj8);
var arrOrdered = _.sortBy(arr, function (item) {
return item; //you could implement your logic in here
});
var html = "";
_.each(arrOrdered, function(item){ html += item + "<br/>";});
document.getElementById('output').innerHTML = html;
}
</script>
</body>
</html>

function load()
{
var arr =new Array();
var obj1 = document.getElementById("txt1").value;
var obj2 = document.getElementById("txt2").value;
var obj3 = document.getElementById("txt3").value;
var obj4 = document.getElementById("txt4").value;
var obj5 = document.getElementById("txt5").value;
var obj6 = document.getElementById("txt6").value;
var obj7 = document.getElementById("txt7").value;
var obj8 = document.getElementById("txt8").value;
arr.push(obj1);
arr.push(obj2);
arr.push(obj3);
arr.push(obj4);
arr.push(obj5);
arr.push(obj6);
arr.push(obj7);
arr.push(obj8);
var arrOrdered = _.sortBy(arr, function (item) {
return item; //you could implement your logic in here
});
iterate.over(arrOrdered);
}

Related

Calculate total sum of all the numbers previously entered in a field

i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">

24hr password array giving syntax errors

I made a script that (should) change the password daily using an array of passwords for each day, but I keep getting all sorts of errors.
<script>
</script>
<form>
<input type="text" placeholder="Username" id="text1" /><br>
<input type="password" placeholder="Password" id="text2" /><br>
<input type="button" class="button4" style="background-color:#9c9c9c" value="Login" onclick="javascript:validate()" />
</form>
<script type="text/javascript">
type = "text/javascript"
window.onload = function() {
chgDailyImg();
}
function chgDailyImg() {
var imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u#2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u#G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ#R";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay();
function validate() {
if (document.getElementById("text1").value == "student21" &&
document.getElementById("text2").value == imagearray[i]) {
console.log("RIGHT")
} else {
console.log("WRONG")
}
}
}
</script>
Mainly, it keeps saying that "validate" is not defined...
"<a class='gotoLine' href='#41:132'>41:132</a> Uncaught ReferenceError: validate is not defined"
OR
"<a class='gotoLine' href='#65:49'>65:49</a> Uncaught ReferenceError: imagearray is not defined"
Your function validate() has a scope within the function chgDailyImg(). Move it outside of the function fixes the problem.
<form>
<input type="text" placeholder="Username" id="text1" /><br>
<input type="password" placeholder="Password" id="text2" /><br>
<input type="button" class="button4" style="background-color:#9c9c9c" value="Login" onclick="javascript:validate()" />
</form>
<script type="text/javascript">
window.onload = function() {
chgDailyImg();
}
const imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u#2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u#G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ#R";
let i = 0;
function chgDailyImg() {
let d = new Date(); /*** create a date object for use ***/
i = d.getDay();
}
function validate() {
if (document.getElementById("text1").value == "student21" &&
document.getElementById("text2").value == imagearray[i]) {
console.log("RIGHT")
} else {
console.log("WRONG")
}
}
</script>
Update:
There are some problems with Scope of your variables and functions. Hope this reading will give you get a better idea.
Scope - MDN Web Docs
https://developer.mozilla.org/en-US/docs/Glossary/Scope

How to fix these undefined values?

So I have a function that I need to pass 3 values, but my values are allways 0 if I don't enter them, and undefined if enter them. How to fix this issue?
<!DOCTYPE html>
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h4>Enter Dimensions</h4>
<input id="a" type="text" name=""><br>
<input id="b" type="text" name=""><br>
<input id="c" type="text" name=""><br>
<input type="button" onclick="calculate()" value="Calculate">
<div id="output"></div>
<script>
var a = Number(document.querySelector('#a').value);
var b = Number(document.querySelector('#b').value);
var c = Number(document.querySelector('#c').value);
function calculate(a, b, c){
//console.log(a);
//console.log(b);
//console.log(c);
return 2*(a*b + a*c + b*c);
}
var p = calculate(a, b, c);
document.querySelector('#output').innerHTML = `<h4>Area = ${p}</h4>`;
</script>
</body>
</html>
You need to get value from elements and set it to #output element each time calculate function is called. Check out my solution below.
var aElement = document.querySelector('#a');
var bElement = document.querySelector('#b');
var cElement = document.querySelector('#c');
var outputElement = document.querySelector('#output');
function updateArea () {
var a = Number(aElement.value);
var b = Number(bElement.value);
var c = Number(cElement.value);
var res = calculate(a, b, c);
outputElement.innerHTML = `<h4>Area = ${res}</h4>`;
}
function calculate (a, b, c) {
return 2*(a*b + a*c + b*c);
}
<h4>Enter Dimensions</h4>
<input id="a" type="text" name=""><br>
<input id="b" type="text" name=""><br>
<input id="c" type="text" name=""><br>
<input type="button" onclick="updateArea()" value="Calculate">
<div id="output"></div>
You are collecting the value of a, b and c at the beginning of the program. At first, the input boxes don't have any value, so the value of a, b and c is undefined. So collect the value when the submit button is clicked.
Try this approach:
function calculate(){
var a = Number(document.querySelector('#a').value);
var b = Number(document.querySelector('#b').value);
var c = Number(document.querySelector('#c').value);
var p = 2*(a*b + a*c + b*c);
document.querySelector('#output').innerHTML = '<h4>Area = ${p}</h4>';
}

Using document.getElementsByTagName, how to get the values of the <input> tags stored in an array/Object?

I am retrieving the form elements in my Javascript, using the document.getElementsByTagName. After that, I am trying to display the content of the input tags and storing in the array or object which I am unable to.
window.onload = function (){
if (document.getElementById("submitid").addEventListener)
{
document.getElementById("submitid").addEventListener("click",function(){
alert(" I m here 1:");
var result = document.getElementsByTagName("input");
// how to retrieve the result variable here ?
for(var i=0;i<result.length;i++)
{
alert("I am here 2");
if(result[i].getAttribute("type")=="text")
{
// trying to get the values in the textbox on console, also how to retrieve and place the same in object
var result1 = result[i];
console.log(result1.innerHTML);
}
}
})
}
};
//the following is the
window.onload = function (){
if (document.getElementById("submitid").addEventListener)
{
document.getElementById("submitid").addEventListener("click",function(){
alert(" I m here 1:");
var result = document.getElementsByTagName("input");
console.log("****** Here " + result);
for(var i=0;i<result.length;i++)
{
alert("I am here 2");
if(result[i].getAttribute("type")=="text")
{
alert("i m here 3");
var result1 = result[i];
console.log(result1.innerHTML);
}
}
})
}
};
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id ="signupForm">
<input type ="text" id ="textid">
<input type="text" id ="textid2">
<input type="submit" id="submitid">
</form>
<script type="text/javascript" src="demo2.js"></script>
</body>
</html>
You need to change the line console.log(result1.innerHTML); with console.log(result1.value); to get hte value of the input:
window.onload = function() {
if (document.getElementById("submitid").addEventListener) {
document.getElementById("submitid").addEventListener("click", function() {
debugger;
alert(" I m here 1:");
var result = document.getElementsByTagName("input");
console.log("****** Here " + result);
for (var i = 0; i < result.length; i++) {
alert("I am here 2");
if (result[i].getAttribute("type") == "text") {
alert("i m here 3");
var result1 = result[i];
console.log(result1.value);
}
}
})
}
};
<html>
<head></head>
<body>
<form id="signupForm">
<input type="text" id="textid">
<input type="text" id="textid2">
<input type="submit" id="submitid">
</form>
<script type="text/javascript" src="demo2.js"></script>
</body>
</html>

Add two numbers and display result in textbox with Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in another text field. But unfortunately the below code is not working. Clicking the button does not show anything in the result text field.
<body>
<div>
<div>
<h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="Text1" name="TextBox1">
<br>
Enter Second Number : <br>
<input type="text" id="Text2" name="TextBox2">
<br>
Result : <br>
<input type="text" id="txtresult" name="TextBox3">
<br>
<input type="button" name="clickbtn" value="Display Result" onclick="add_number()">
<script type="text/javascript">
function add_number(){
var first_number = parseInt(document.getElementsById("Text1").value);
var second_number = parseInt(document.getElementsById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").innerHTML = result;
}
</script>
Here a working fiddle: http://jsfiddle.net/sjh36otu/
function add_number() {
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}
When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
// This is because your method .getElementById has the letter 's': .getElement**s**ById
<script>
function sum()
{
var value1= parseInt(document.getElementById("txtfirst").value);
var value2=parseInt(document.getElementById("txtsecond").value);
var sum=value1+value2;
document.getElementById("result").value=sum;
}
</script>
You made a simple mistake. Don't worry....
Simply use getElementById instead getElementsById
true
var first_number = parseInt(document.getElementById("Text1").value);
False
var first_number = parseInt(document.getElementsById("Text1").value);
Thanks ...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.minus = function() {
var a = Number($scope.a || 0);
var b = Number($scope.b || 0);
$scope.sum1 = a-b;
// $scope.sum = $scope.sum1+1;
alert($scope.sum1);
}
$scope.add = function() {
var c = Number($scope.c || 0);
var d = Number($scope.d || 0);
$scope.sum2 = c+d;
alert($scope.sum2);
}
});
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h3>Using Double Negation</h3>
<p>First Number:
<input type="text" ng-model="a" />
</p>
<p>Second Number:
<input type="text" ng-model="b" />
</p>
<button id="minus" ng-click="minus()">Minus</button>
<!-- <p>Sum: {{ a - b }}</p> -->
<p>Sum: {{ sum1 }}</p>
<p>First Number:
<input type="number" ng-model="c" />
</p>
<p>Second Number:
<input type="number" ng-model="d" />
</p>
<button id="minus" ng-click="add()">Add</button>
<p>Sum: {{ sum2 }}</p>
</div>
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>
It should be document.getElementById("txtresult").value= result;
You are setting the value of the textbox to the result. The id="txtresult" is not an HTML element.
<script>
var text1 = document.getElementById("Text1").value;
var text2 = document.getElementById("Text2").value;
var answer = parseInt(text1) + parseInt(text2);
function add_number(){
document.getElementById("txtresult").value = answer;
}
</script>
its Not document.getElementsById function its document.getElementById try it
Instead of writing
.innerHTML = result;
use
.value = result;
<html lang = "en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator DEMO</title>
</head>
<body>
<div>
<p>
<label>Enter Number 1: </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Number 2: </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="resultsum()">+</button>
<button onclick="resultsub()">-</button>
<button onclick="resultmul()">*</button>
</p>
<p>
<button onclick="resultdiv()">/</button>
<button onclick="resultmod()">%</button>
<button onclick="resultper()">percentage</button>
</p>
<script>
function resultsum()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var sm = y + z;
document.getElementById("resultsum").innerHTML = sm;
if(document.getElementById("resultsum").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultsub()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var sb = y - z;
document.getElementById("resultsub").innerHTML = sb;
{
if(document.getElementById("resultsub").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
}
function resultmul()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var ml = y * z;
document.getElementById("resultmul").innerHTML = ml;
if(document.getElementById("resultmul").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultdiv()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var dv = y / z;
document.getElementById("resultdiv").innerHTML = dv;
if(document.getElementById("resultdiv").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultmod()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var md = y + z;
document.getElementById("resultmod").innerHTML = md;
if(document.getElementById("resultmod").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultper()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var per = (y + z )/2;
document.getElementById("resultper").innerHTML = per;
if(document.getElementById("resultper").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
</script>
<input type="text" name="Answers" id="ans" >
<br/>
<p id="resultsum"></p>
<p id="resultsub"></p>
<p id="resultmul"></p>
<p id="resultdiv"></p>
<p id="resultmod"></p>
<p id="resultper"></p>
</div>
</body>
</html>
You can simply convert the given number using Number primitive type in JavaScript as shown below.
var c = Number(first) + Number(second);

Categories