Checkboxes and localStorage - javascript

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!
New to all this so be gentle please.
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
function save() {
//enter iteration sequence
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>

To retrieve all elements you can use document.querySelectorAll and pass as argument the filter that will do the job. In this case you want to retrieve all htlm elements that have the type attribute value equals to checkbox. After the retrieval of all elements that have type="checkbox", you should traverse all elements of list. And for each element you should store the id of checkbox as key and the checked of the checkbox asvalue in localstorage.
Below is the code:
<script>
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
And below is the code for updating the checkboxes with value we stored in localstorage.
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99.com/cookies-in-javascript-ultimate-guide.html.
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
VERSION WITH LOCAL STORAGE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
</body>
</html>
VERSION WITH COOKIE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(accessCookie(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
createCookie(el.id, el.checked,1);//1 is the day to expire
console.log(el.id,el.checked);
})
}
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
</script>
</body>
</html>

Just pass a different id in to document.getElementById.
Make sure to use a different key for localStorage.setItem so you don't overwrite a different value.
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.
Alternatively you could use a for loop and loop for as many items as you wish to save

On every save you can create an object with checkbox identification and values, save t in localStorage, on reloading, get the the whole object by a single key, parse it, loop through and set values
function save() {
//enter iteration sequence
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var obj = {};
for (i = 0; i < checkboxes.length; i++) {
obj[checkboxes[i].id] = checkboxes[i].checked
}
localStorage.setItem("box", JSON.stringify(obj));
}
//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);

Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.
Your code with fixing script
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />
<script>
function save() {
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checkbox2 = document.getElementById("whatever-2");
localStorage.setItem("whatever-2", checkbox2.checked);
}
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked;
</script>

Related

how do I check dynamically generated radio input value

I have to generate multiple input fields dynamically for each time user clicks "add" button and I was successfully able to get them. Each contact should have this radio input field in different different name so I've created a name in an array form.
Here's what I have so far and I wonder how I'm supposed to get the radio value for each person:
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
options = '<p>Visit Type:
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Student" required>Student</label>
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$(options).fadeIn("slow").appendTo('.companion');
return false;
}
});
$('.c_visittype' + count).on('click', function(){
$('input:radio[name="c_visittype"]').attr('checked', 'checked');
});
Each person should get a choice of either 'student' or 'visitor' and I have to get this value for multiple persons whenever more person fields created.The reason why I put field's name as an array is to iterate it in the next page by php.
<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
var options = '<p style="display: none">Visit Type:<label class="radio-inline"> <input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Student" required>Student</label> <label class="radio-inline"><input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$('.companion').append(options);
$(".companion p:last").fadeIn();
}
});
});
</script>
<button id="add">add</button>
<div class="companion">
</div>
$('input[name=c_visittype[]]:checked').val();
That's how you access the value of a checked radio button with jQuery.
var inputValues = [];
$('.c_visittype:checked').each(function() {
inputValues.push($(this).val());
});
// Your code using inputValues
For update on changes:
$(function() {
$('.c_visittype').click(function(){
// Insert code here
}
)});
Make sure to move the numbering from the class attribute to the name attribute (like it was, everything was part of the same set of options). Also, put the whole string on 1 line.

Javascript add cookie

I am fairly new to javascript and not really sure what I am doing. Right now I am trying to add textbox data as well as some strings to cookies to display on another page. The textbox part is working.
For the strings, I am taking the value of a radio button (for a multiple choice quiz validation) and if the value is the correct value for that group, I would like to add a string to cookies. I can't figure out what I am doing wrong for this part.
Specifically what isn't working is the content in the gradeit() function
JS file
var total = 5;
var right = 0;
//cookies
function addToCookie(id, value)
{
document.cookie = id + escape(value);
}
var grade=new Array()
function gradeit(){
if(document.getElementById('correctOne').checked)
{
right++;
addToCookie("Q1 - Correct",right);
}
else {addToCOokie("Q1 - Incorrect", right);}
}
function checkCookie() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
addToCookie("First Name= ",firstName);
addToCookie("Last Name= ",lastName);
addToCookie("Email=",email);
}
window.onload = function () {
var elem = document.getElementById("submit");
elem.addEventListener('click', checkCookie);
}
// determine whether there is a cookie
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
var result = "";
// Now take key value pair out of this array
for (var i = 0; i < cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
result +=( name + " is : " + value)+"<br>";
}
document.writeln(result);
HTML PAge
<DOCTYPE HTML5>
<html>
<head>
<meta charset="utf-8">
<title>Quiz</title>
<script src="cookies.js" type="text/javascript"></script>
</head>
<body>
<h1><b>Multiple Choice Quiz</b></h1>
<form name="myquiz" action="answers.html" method="post">
<h2>Please Enter the Following:</h2>
First Name: <input type="text" id="fname"></input>
Last Name: <input type="text" id="lname"></input><br><br>
Student Email: <input type="email" id="email"></input>
<br>
<h3>#1. What is the capital of Iowa?</h3>
<input type="radio" name="question1" id="correctOne">Des Moines</input>
<input type="radio" name="question1" id="wrong">Los Angeles</input>
<input type="radio" name="question1" id="wrong">Paris</input>
<input type="radio" name="question1" id="wrong">Tokyo</input>
<br><br>
<input type="submit" id="submit" value="Submit Answers" onClick="gradeit()"></input>
</form>
</body>
</html>
I just got it to work by modifying my gradeit() function this way:
function gradeit(){
var ans = "";
if(document.getElementById('correctOne').checked)
{
//document.getElementById("output").innerHTML = "Q1 - Correct";
right++;
ans ="Right";
addToCookie("Q1 - ", ans);
}
else {
ans ="Wrong";
addToCookie("Q1 - ", ans);
}
}

5 radio buttons fill up randomly?

Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly.
It's like a random generator for stats for a game.
I don't know if I'm doing it all wrong but I think I need some other coding for this.
Can anyone that can help me?
This is what I have:
<button onclick='myFunction()'>click me</button>
<div id="demo">
<Input type = radio Name = r1>
<Input type = radio Name = r2>
<Input type = radio Name = r3>
<Input type = radio Name = r4>
<Input type = radio Name = r5>
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById('demo').innerHTML = '';
var num = 3;
var noOfButtons = Math.floor(Math.random() * num);
console.log(noOfButtons);
for (var i = 0; i < noOfButtons; i++) {
var box = document.createElement();
document.getElementById('demo');
}
}
</script>
not exactly sure what your looking for. I threw this JSFiddle together. Take a look and see if its what you're looking for.
<button id='button1'>click me</button>
<div id="demo">
<input type='radio' id='r1'>
<input type='radio' id='r2'>
<input type='radio' id='r3'>
<input type='radio' id='r4'>
<input type='radio' id='r5'>
</div>
.
var button1 = document.getElementById('button1');
button1.onclick = function () {
var noOfButtons = 5;
var pick = Math.floor(Math.random() * noOfButtons) + 1;
var radioBtn = document.getElementById('r' + pick);
radioBtn.checked = true;
}
[edit]
I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:
function myFunction() {
var radios = document.getElementsByClassName('myRadios');
for (var i=0; i<radios.length; i++)
{
radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
}
}
Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

Variable not updating

I have 2 files, my index and my JS file.
In my index I will have a form of input fields and my index file will be linked to my JS file.
In my JS file I will have a list of variables which will get their values from my index file input fields. I plan on then multiplying some of my values together in a function.
What is the correct way of doing this without returning NaN or undefined?
I've been trying to do by setting var values onkeyup or onclick as 'document.getelementbyid' only it never returns anything...
Some sample code would be,
HTML
<input type="radio" id="ServiceLevel" value="0.84" name="ServiceLevel"onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.67" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.56" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.28" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.14" name="ServiceLevel" onclick="getValue()"/>
and JS
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed(2));
}
You need to get the values in the javascript. Here is how you should do
Create a file index.htm
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
script.js
function Calculate()
{
var v1 = document.getElementById ("a1").value;
var v2 = document.getElementById ("a2").value;
var v3 = document.getElementById ("a3").value;
var total = GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
first thing is
var ServiceLevel = document.getElementById(ServiceLevel).value;
// ServiceLevel = null
this should be in function else while opening this web page getElementById will give null.
2
. your input radio button has same name & ID if this is the case which value should be taken OR they are Individual OR Group
I tried this check:
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}

Categories