Good morning. Improving this code I found it difficult to insert a custom radio with fonts.googleapis to show after the quiz verification function. Something like the attached image Do you have any suggestions? or better yet an example of code.... heartfelt thanks to the community, I wish you a good day to all and happy coding
var answers = ["1b"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
}
else if (checked) {
rad.closest("label").classList.toggle("error")
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
border-left: 2px solid green;
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
border-left: 2px solid red;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
var answers = ["1b", "1c"];
var rads, quiz, cur, par;// need to be set after load
var ShowAnswer = true; // Try false
window.addEventListener("load", function() {
// when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document
.getElementById("scoreButton")
.addEventListener("click", function(e) {
// on click of scoreme
cur = quiz.querySelector("input[type=radio]:checked");
par = cur.parentNode;
var score = 0;
for (var i = 0; i < rads.length; i++) {
// loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = !(answers.indexOf(cur.getAttribute("value")) == -1);
rad.style.appearance = 'none';
document.getElementById("scoreButton").style.display = 'none';
if (!(answers.indexOf(rad.getAttribute('value')) == -1) && ShowAnswer) {
rad.parentNode.classList.add("correct");
rad.parentNode.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
rad.parentNode.innerHTML;
}
if (correct) {
par.classList.add("correct");
par.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
par.innerHTML;
} else if (checked) {
par.classList.add("error");
par.innerHTML =
`<span class="material-icons-round error e">close</span>` +
par.innerHTML;
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
}
.c {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
}
.e {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG But shown as right due to value in js</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
Here is a PEN
Edited with replacement of choose option hiding!
Related
I'm trying to have my form show child elements if the parent is visible and I keep getting an "undefined" error with my child element, even though I have it defined. I'm trying to have set this up where:
Q1: Checked responses will show parent elements (divs).
Q2: Depending on this response, it'll show child elements (divs).
Is there a way to do this?
//Next Tab
function next() {
var formTabOne = document.getElementById("stepOne");
formTabOne.classList.add("formTrans");
formTabOne.addEventListener("transitionend", function({
target
}) {
if (target === formTabOne) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepTwo").classList.remove("hidden");
}
})
}
//Prev Tab
function prev() {
var formTabTwo = document.getElementById("stepTwo");
formTabTwo.classList.add("formTrans");
formTabTwo.addEventListener("transitionend", function({
target
}) {
if (target === formTabTwo) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepOne").classList.remove("hidden");
}
})
}
function process() {
var form = document.myForm;
var biz = document.getElementById("biz");
var career = document.getElementById("career");
var change = document.getElementById("change");
var eq = document.getElementById("eq");
var empathy = document.getElementById("empathy");
var pm = document.getElementById("pm");
var bizMgr = document.getElementsByClassName("bizMgr");
var bizEE = document.getElementsByClassName("bizEE");
//Q1 - Topics
document.querySelectorAll("#chkTopic input").forEach((el) => {
const contentID = el.id.replace("chk", "").toLowerCase()
document.getElementById(contentID).style.display = el.checked ? "block" : "none";
});
//Q2 - Employee Type
var q2value = "";
for (var i = 0; i < form.q2.length; i++) {
var answer = form.q2[i];
if (answer.checked) {
q2value = answer.value;
}
}
if (q2value == "1") {
if (biz.style.display = "block") {
bizMgr.style.display = "block";
bizEE.style.display = "block";
}
} else {
if (biz.style.display = "block") {
document.getElementsByClassName("bizEE").style.display = "block";
}
}
}
html {
scroll-behavior: smooth;
}
#formWrapper {
background-color: #eaeaea;
padding: 20px;
margin-bottom: 40px;
min-height: 300px;
}
#myForm {
width: 70%;
min-height: 280px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border: 1px solid #dedede;
box-sizing: border-box;
}
.formStep {
opacity: 1;
background: #fff;
}
.formTrans {
visibility: hidden;
opacity: 0;
transition: visibility 0s 200ms, opacity 200ms linear;
}
.hidden {
display: none;
}
#biz, #career, #change, #eq, #empathy, #pm, #pd {
display: none;
width: 100%;
min-height: 200px;
box-sizing: border-box;
margin-bottom: 30px;
border: 1px solid #000;
}
.bizMgr, .bizEE, .careerMgr, .careerEE, .changeMgr, .changeEE, .eqMgr, .eqEE, .empathyMgr, .empathyEE, .pmMgr, .pmEE, .pdMgr, .pdEE {
display: none;
}
<form name="myForm" id="myForm">
<input type="button" value="Skip This" onclick="formSkip();">
<br><br>
<!--Step 1-->
<div id="stepOne" class="formStep">
<b>Select the topic(s) you're interested in:</b><br>
<div id="chkTopic">
<input id="chkBiz" type="checkbox" value="1"><label for="chkBiz">Business Structure/Acumen</label><br>
<input id="chkCareer" type="checkbox" value="2"><label for="chkCareer">Career Development</label><br>
<input id="chkChange" type="checkbox" value="3"><label for="chkChange">Change</label><br>
<input id="chkEQ" type="checkbox" value="4"><label for="chkEQ">Emotional Intelligence</label><br>
<input id="chkEmpathy" type="checkbox" value="5"><label for="chkEmpathy">Empathy</label><br>
<input id="chkPM" type="checkbox" value="6"><label for="chkPM">Performance Management</label><br>
</div>
<br>
<button type="button" id="btnStepOne" onclick="next();">Next</button>
</div>
<!--Step 2-->
<div id="stepTwo" class="formStep hidden">
<b>Are you a people leader?</b><br>
<input type="radio" name="q2" value="0">No<br>
<input type="radio" name="q2" value="1">Yes<br>
<br>
<button type="button" id="btnStepTwo" onclick="prev();">Previous</button>
<input type="button" value="Show Results" onclick="process();">
<input type="reset" value="Start Over" onclick="formReset();">
</div>
</form>
<div id="results">
<div id="biz">
Business Structure/Acumen
<div class="bizMgr">Manager Content</div>
<div class="bizEE">Employee Content</div>
</div>
<div id="career">
Career Development
<div class="careerMgr">Manager Content</div>
<div class="careerEE">Employee Content</div>
</div>
<div id="change">
Change
<div class="changeMgr">Manager Content</div>
<div class="changeEE">Employee Content</div>
</div>
<div id="eq">
Emotional Intelligence
<div class="eqMgr">Manager Content</div>
<div class="eqEE">Employee Content</div>
</div>
<div id="empathy">
Empathy
<div class="empathyMgr">Manager Content</div>
<div class="empathyEE">Employee Content</div>
</div>
<div id="pm">
Performance Management
<div class="pmMgr">Manager Content</div>
<div class="pmEE">Employee Content</div>
</div>
</div>
.getElementsByClassName returns a collection, bizMgr and bizEE are both collections. You have to iterate the collections and set each element to style.display = 'block'. You can't just call xxx.style.display on a javascript collection. You would want to change your code like the following:
if (q2value == "1") {
if (biz.style.display = "block") {
//bizMgr.style.display = "block"; -NO
//bizEE.style.display = "block"; -NO
for(let i = 0; i < bizMgr.length; i++){
bizMgr[i].style.display = "block";
}
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
} else {
if (biz.style.display = "block") {
//document.getElementsByClassName("bizEE").style.display = "block"; -NO
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
}
Trying to make an if statement in JS that when one of the top 3 buttons changes, it checks which of the bottom 2 has the "active" class, and visa versa.
So when I click 30g it will check if option a or option b is active, and then change the price accordingly.
Any help would be greatly appreciated as I'm kind of a noob.
The problem is there are 2 rows of buttons (one to select the weight, and one to select option a or b). I know how it would work, I just don't know the syntax, this is what I want to happen but it's not coded right.
//this is shitty code of what I mean, but I don't know how to code in JS
if(button30g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=1.00; }
else if(button30g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=2.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
<!DOCTYPE html>
<html lang="en">
<head>
<style>
ul.nav a{
border: 2px solid #E1E8EE;
border-radius: 6px;
padding: 13px 20px;
font-size: 14px;
color: #5E6977;
background-color: #fff;
cursor: pointer;
transition: all .5s;
display: inline-block;
vertical-align: middle;
}
.activeBtn { color:grey; font-weight:1000; border: 2px solid grey; border-radius: 6px; }
</style>
</head>
<body>
<ul class="nav">
<li id="30" data-price="bird" onclick="myFunction()" class="activeBtn"><a>30g</a></li>
<li id="70" onclick="myFunction()"><a>70g</a></li>
<li id="90" onclick="myFunction()"><a>90g</a></li>
</ul>
<ul class="nav">
<li id="no" class="activeBtn"><a>option a</a></li>
<li id="yes"><a>option b</a></li>
</ul>
<br>
<div class="product-price">
<span id="price">148$</span>
</div>
</body>
<footer>
<script>
$(function() {
$( 'ul.nav li' ).on( 'click', function() {
$( this ).parent().find( 'li.activeBtn' ).removeClass( 'activeBtn' );
$( this ).addClass( 'activeBtn' );
});
});
</script>
<script>
function myFunction() {
const element = document.getElementById("30");
const element2 = document.getElementById("no");
const pricetag = document.getElementById("price");
if(((element.classList.contains("activeBtn"))==true)&&((element2.classList.contains("activeBtn"))==true))
{
pricetag.innerHTML = €1,00;
}
</script>
</footer>
</html>
The work that you want I have done it separately so check this out. This code works according to the option "yes" or "no" and shows the price.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.radioStyle{
border-color: blue;
border-width: thin;
border-style: solid;
width: 50%;
}
</style>
</head>
<body>
<div><input type="radio" name="grams" value="30" id = "30" onclick="myFunction()"> 30g</div>
<div><input type="radio" name="grams" value="70" id = "70" onclick="myFunction()"> 70g</div>
<div><input type="radio" name="grams" value="90" id = "90" onclick="myFunction()"> 90g </div>
<hr>
<input type="radio" name="option" value="yes" id ="yes" checked onclick="myFunction()"> yes<br>
<input type="radio" name="option" value="no" id = "no" onclick="myFunction()"> no<br>
<br>
<span id = "sp">
0$
</span>
</body>
<footer>
<script>
function setBorder(){
var siblings = document.querySelectorAll('input[name = "grams"]');
siblings.forEach(element => element.parentElement.className="");
var grams = document.querySelector('input[name = "grams"]:checked');
grams.parentElement.className = "radioStyle";
console.log(siblings);
console.log(grams);
}
function myFunction(){
setBorder();
var grams = document.querySelector('input[name = "grams"]:checked').value;
var option = document.querySelector('input[name = "option"]:checked').value;
var rate = 0;
if (option == "yes"){
if (grams == "30")
rate = 1.5;
else if (grams == "70")
rate = 2.5;
else if (grams == "90")
rate = 3.5;
}
else if (option == "no"){
if (grams == "30")
rate = 2;
else if (grams == "70")
rate = 3;
else if (grams == "90")
rate = 4;
}
document.getElementById("sp").innerHTML = rate*grams+"$";
}
</script>
</footer>
</html>
I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var tasks = [];
var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";
// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}
// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};
var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {
// add task to array and local storage
tasks.push(task.value);
localStorage.tasks = tasks.join("|");
// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};
window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 700px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Ch09 Task Manager</title>
<link type="text/css" rel="stylesheet" href="task_list.css">
<script type="text/javascript" src="task_list.js"></script>
</head>
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
</body>
</html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that.
var tasks = [];
var displayTaskList = function() {
var list = "";
if (tasks.length === 0) { // if there are no tasks in tasks array, check storage
var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage
if (storage.length > 0) {
tasks = storage.split("|");
} // if not empty, convert to array and store in global tasks variable
}
if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string
tasks.sort();
list = tasks.join("\n");
}
$("#task_list").val(list); // display tasks string and set focus on task text box
$("#task").focus();
};
var addToTaskList = function() {
var task = $("#task").val();
console.log(`entering addtotask list with task value = ${task}`);
if (task === "") {
alert("Please enter a task.");
} else {
if (task.indexOf(',') === -1) {
tasks.push(task); // add task to array and local storage
} else {
const split = task.split(','); // 2 lines for readability
split.forEach(atask => {
tasks.push(atask);
});
}
localStorage.tasks = tasks.join("|");
$("#task").val(""); // clear task text box and re-display tasks
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("#task_list").val("");
$("#task").focus();
};
window.onload = function() {
$("#add_task").on('click', function() {
addToTaskList();
});
$("#clear_tasks").on('click', function() {
clearTaskList();
});
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</body>
I tried searching on the internet for answer but the closest I can find is in this jfiddle
What I wanted to do is when the page loads, the textbox is automatically filled with this words Furniture/Chair/Square. In addition, the user can input some text next to the words like this Furniture/Chair/Square/_ _ _/_ _ _. The user cannot erase the automatically filled words.
This is a work around with some reference from jwa's post and RegEx:
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
How do I include numbers?
Use [^a-z0-9] in this line this.value.replace(/[^a-z]/gi, '')
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z0-9]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
You can do this by assigning a label to the input field you create. For example...
#text-input {
border: none;
outline: none;
}
label{
border:solid 1px black;
padding-right: 2px;
}
<label for="text-input">
furniture chair square
<input type="text" id="text-input" />
</label>
Use RegExp to solve your problem.
You may add some css or addition text to notice the user error input.
function checkStr(str){
//check pattern
result = str.match(/^Furniture\/Chair\/Square([a-zA-Z\/]+)?/)
if(result == null || result[0].length !== str.length){
//revert the input field to default
document.getElementById('userText').value = "Furniture/Chair/Square"
}
}
<input type="text" value="Furniture/Chair/Square" id="userText" oninput="checkStr(value)"></input>
<p id='asd'></p>
<!DOCTYPE HTML>
<html>
<head>
<title>HTML5 localStorage (name/value item pairs) demo</title>
<style >
td, th {
font-family: monospace;
padding: 4px;
background-color: #ccc;
}
#hoge {
border: 1px dotted blue;
padding: 6px;
background-color: #ccc;
margin-right: 50%;
}
#items_table {
border: 1px dotted blue;
padding: 6px;
margin-top: 12px;
margin-right: 50%;
}
#items_table h2 {
font-size: 18px;
margin-top: 0px;
font-family: sans-serif;
}
label {
vertical-align: top;
}
</style>
</head>
<body onload="doShowAll()">
<h1>HTML5 localStorage (name/value item pairs) demo</h1>
<form name=editor>
<div id="hoge">
<p>
<label>Value: <textarea name=data cols=41 rows=10></textarea></label>
</p>
<p>
<label>Name: <input name=name></label>
<input type=button value="getItem()" onclick="doGetItem()">
<input type=button value="setItem()" onclick="doSetItem()">
<input type=button value="removeItem()" onclick="doRemoveItem()">
</p>
</div>
<div id="items_table">
<h2>Items</h2>
<table id=pairs></table>
<p>
<label><input type=button value="clear()" onclick="doClear()"> <i>* clear() removes all items</i></label>
</p>
</div>
<script>
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
function doGetItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.getItem(name);
doShowAll();
}
function doRemoveItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.removeItem(name);
doShowAll();
}
function doClear() {
localStorage.clear();
doShowAll();
}
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var i=0;
for (i=0; i<=localStorage.length-1; i++) {
key = localStorage.key(i);
pairs += "<tr><td>"+key+"</td>\n<td>"+localStorage.getItem(key)+"</td></tr>\n";
}
if (pairs == "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
</script>
</form>
</body>
</html>
Hi friends,
I wants to locally save the data,now I am able to save the data locally by the code.even if I give the same name the value is getting added and saved locally.but the name should be shown in order of high value to low(example: Ram 20,Renu 18,green 2 like wise...).so how to do this?
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
To display them in descending order:
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var userArray = [];
for (var i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
userArray.push({name:key, value:parseInt(localStorage.getItem(key))});
}
userArray.sort(function(a, b){
return b.value - a.value;
});
userArray.forEach(function(user){
pairs += "<tr><td>" + user.name + "</td>\n<td>" + user.value + "</td></tr>\n";
});
if (pairs === "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
For what I can see in your code, you're just replacing the value, you need to get the existent value from the localStorage first, append to it the new one and then asign the result to the localStorage.