I don't know if I have understood the right context of 'storage', but according to some tutorials I used the following Javascript code, to enable a page to locally store (no session) submitted data, but when I close the page and reopen the page, the content do not appear.
script.js
function initiate()
{
var saveButton = document.getElementById('save');
var retrieveButton = document.getElementById('retrieve');
var deleteButton = document.getElementById('delete');
var reviewButton = document.getElementById('review');
saveButton.addEventListener('click', saveItem);
retrieveButton.addEventListener('click', retrieveItem);
deleteButton.addEventListener('click', deleteItem);
reviewButton.addEventListener('click', reviewAll);
}
function saveItem()
{
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage[key] = value;
}
function retrieveItem()
{
var data = document.getElementById('data');
var key = document.getElementById('key').value;
var value = localStorage[key];
data.innerHTML = '<div>' + key + ': ' + value + '</div>';
}
function deleteItem()
{
if (confirm('Delete?'))
{
var key = document.getElementById('key').value;
localStorage.removeItem(key);
data.innerHTML = '<div>Deleted.</div>';
}
}
function reviewAll()
{
for(var i = 0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var value = localStorage[key];
data.innerHTML += '<div>' + key + ': ' + value + '<br></div>';
}
}
addEventListener("load", initiate);
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="mystyles.css" />
<script src="script.js"></script>
<title>Demo HTML5</title>
</head>
<body>
<section id="formSection">
<form name="dataForm">
<label for="key">Key: </label><br />
<input type="text" id="key" name="key" /> <br />
<label for="value">Value: </label><br />
<textarea name="value" id="value"></textarea><br />
<input type="button" id="save" value="Save" />
<input type="button" id="retrieve" value="Retrieve" />
<input type="button" id="delete" value="Delete" />
<input type="button" id="review" value="Review" />
</form>
</section>
<section id="data">
No data
</section>
</body>
</html>
If you are using the browser in privacy mode, it will clear all localStorage data when you close it.
Related
I am trying to get the values from the added input fields and display it in the textarea.
The values of the input fields will be added once the codeBtn has been clicked and will add it in the textarea. I only have managed to get the values from the first input fields that has been created in HTML.
Moreover, I have tried to add the new value input fields.
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val();
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
But this will give me 'undefined' when I only want to display the values of titleInput1 and contentInput1.
Basically what I'm trying is to get the values from each added input fields to the textarea.
Can anyone please help me? Thank you
Sample HTML Code:
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<label for="">Titel:</label>
<input type="text" id="titleInput1">
<label for="">Content:</label>
<input type="text" id="contentInput1">
</div>
<div class="newInputs">
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
JQuery Code:
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<label for="">Titel:</label>
<input type="text" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" id="contentInput`
const defaultInput_lastpart = `">`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
let titleValue1 = $('#titleInput1').val();
let contentValue1 = $('#contentInput1').val()
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val()
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
Instead using dynamically created id use classes to get inputs value.
Below is the example
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<div class="nwlist"><label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput`
const defaultInput_lastpart = `"></div>`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
totalString = "";
$(".nwlist").each(function(){
totalString = totalString + $(this).find(".titleInput").val() + " " + $(this).find(".contentInput").val() + " ";
})
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<div class="nwlist">
<label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput1">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput1">
</div>
<div class="newInputs">
</div>
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
</body>
</html>
Hope it will help.
I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name"
/></label></p>
<p><label>Age: <input class="text" type="text" id="age" /> c
</label></p>
<p><label>Position: <input class="text" type="text"
id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details"
maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick=""
value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
var employees = [];
and my Javascript
//-------------------------------------------------------------------------
-------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//------------------------------------------------------------------------
-----------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//-------------------------------------------------------------------------
-------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------
------------------------------------
function sortAge(){
}
//-------------------------------------------------------------------------
-------------------------------------
function addRecord(){
}
//-------------------------------------------------------------------------
-------------------------------------
function writeRecords(){
//-------------------------------------------------------------------------
------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------
------------------------------------
function arrayButtons(){
}
You can do something like this.
elements = document.getElementById("myForm").elements;
for (var i = 0; i < elements.length; i++) {
var name = elements[i].name;
var val = elements[i].value;
name = name[0].toUpperCase() + name.slice(1);
var dsply = document.getElementById("dsply");
dsply.innerHTML += "<p>" + name + ": " + val + "</p>";
}
<form id="myForm" name="myForm">
<p>Title of the form</p>
<input type="text" name="user" value="Jon" />
<input type="age" name="age" value="26" />
<input type="text" name="pos" value="CEO" />
<textarea name="details">Enter Details here</textarea>
</form>
<div id="dsply">
</div>
I am trying to create "quicklink" option in textarea using which users can insert html tags by directly clicking over them. It is working fine but after I click any quicklink button the cursor moves to the end of the text present in the textarea.
How to keep/focus cursor just after the inserted tag?
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
// Getting closest number for array
// https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
$('#txtarea').click(function(){
var str = $(this).val();
var regex = /\<([a-zA-Z\/]+\>)/gi, result, indices = [];
// Getting positions as array
// https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
var cursorPosition = $(this).prop("selectionStart");
$(this).prop('selectionEnd');
var closestPosition = closest(cursorPosition,indices)
$(this).prop('selectionEnd', closestPosition);
})
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
You can get current cursor position by using following solution:
https://stackoverflow.com/a/1909997/7676742
And increment it by the length of your new added html tag (for instance 3 for <a>) and set position of cursor by using following solution:
https://stackoverflow.com/a/49750025/7676742
I found an easy way to do this:
function quicklink(link){
var linklen=link.length;
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").prop('selectionEnd', cursorPos+linklen);
$("#textarea").focus();
}
I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
and here's my Javascript:
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//-----------------------------------------------------------------------------------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//--------------------------------------------------------------------------------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------------------------------------------
function sortAge(){
}
//--------------------------------------------------------------------------------------------------------------
function addRecord(){
}
//--------------------------------------------------------------------------------------------------------------
function writeRecords(){
//--------------------------------------------------------------------------------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------------------------------------------
function arrayButtons(){
}
I understand there's probably a lot of simple mistakes and stuff missing but i'm really having trouble grasping this,
Kind regards
I'm new in coding , there is a question that someone gave me and I can't find the right answer , this is the question :
Create an HTML form with one field and button.On button click,get the input,and return the sum of the previous value and the current input value.The value is 0 and input is 5->output is 5,then value is 5,input is 6-> output is 11 and etc.
I tried few things nothing even close ,
if someone can give me the answer Ill be much appreciated , thanks.
There you go, but you should try doing it yourself. it's pretty easy to google things like "on button click" etc.
var total = 0;
$('.js_send').click(function(){
total += parseInt($('.number').val());
$('.total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" class="number"/>
<input type="button" value="send" class="js_send"/>
<div class="total">0</div>
Here's a JQuery free version
var oldInput = 0,
newInput,
outPut;
document.querySelector("#showSum").onclick = function() {
newInput = parseInt(document.querySelector("#newInput").value),
outPut = newInput + oldInput,
oldInput = outPut,
document.querySelector("#result").innerHTML = outPut;
};
#result {
width: 275px;
height: 21px;
background: #ffb6c1;
}
<input type="number" value="0" id="newInput">
<button id="showSum">Show Results</button>
<br>
<div id="result"></div>
Here is the solution to your problem. Put all below code into a html file and name it as index.html, then run the html page.
<html>
<head>
<title></title>
</head>
<body>
Output : <label id="output">0</label>
<form method="get" action="index.html">
Your Input: <input type="text" id="TxtNum"/>
<input type="hidden" id="lastvalue" name="lastvalue" />
<input type="submit" onclick="return doSum();" value="Sum" />
</form>
<script>
//- get last value from querystring.
var lastvalue = getParameterByName('lastvalue');
if (lastvalue != null) {
document.getElementById("lastvalue").value = lastvalue;
document.getElementById("output").innerHTML = lastvalue;
}
/*
* - function to calculate sum
*/
function doSum() {
var newvalue = 0;
if(document.getElementById("TxtNum").value != '')
newvalue = document.getElementById("TxtNum").value;
var lastvalue = 0;
if(document.getElementById("lastvalue").value != '')
lastvalue = document.getElementById("lastvalue").value;
document.getElementById("lastvalue").value = parseInt(newvalue) + parseInt(lastvalue);
output = parseInt(newvalue) + parseInt(lastvalue);
}
/*
* - function to get querystring parameter by name
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</body>
</html>
If you are doing it in server side, You could have a static variable and update it on button click. More like
public static int prevValue;
public int buttonclick(.....){
int sum = textboxValue + prevValue;
prevValue = textboxValue;
return sum;
}
here is your solution
<script type="text/javascript">
var sum=0;
function summ()
{
localStorage.setItem("value",document.getElementById("text").value);
var v=localStorage.getItem("value");
sum=sum+parseInt(v);
alert(sum);
}
</script>
<html>
<input id="text">
<button id="submit" onclick="summ()">sum</button>
</html>
It will be pretty easy.
Created CodePen
http://codepen.io/anon/pen/eJLNXK
function getResult(){
var myinputValue=document.getElementById("myinput").value;
var resultDiv=document.getElementById("result");
if(myinputValue && !isNaN(myinputValue)){
resultDiv.innerHTML=parseInt(myinputValue) + (resultDiv.innerHTML ? parseInt(resultDiv.innerHTML) : 0);
}
}
<input type="text" id="myinput">
<button id="btngetresult" onclick="getResult()">GetResult</button>
<p>
Result:
<div id="result"></div>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function sum() {
var t1 = parseInt(document.getElementById("t1").value);
var t2 = parseInt(document.getElementById("pre").value);
document.getElementById("result").innerHTML = t1+t2;
document.getElementById("pre").value = t1;
}
</script>
</head>
<body>
<div>
<form method="get" action="">
<input type="text" name="t1" id="t1">
<input type="button" value="get sum" name="but" onclick="sum()">
<input type="hidden" name="pre" id="pre" value="0">
</form>
</div>
<div id="result"></div>
</body>
</html>