localStorage how to save a checkbox - javascript

I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on the checkbox and i press the save button it doesn't save the checkbox.
how can i achieve this?
this is my code:
<script>
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
if(document.getElementById('checkbox1zaal1').checked) {
localStorage.setItem('checkbox1zaal1', true);
}
}
function load(){
var checked = localStorage.getItem('checkbox1zaal1');
if (checked == true) {
document.getElementById("checkbox1zaal1").setAttribute('checked','checked');
}
}
function wis(){
location.reload();
localStorage.clear()
}
</script>
<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1">1e film van de dag</input>
</body>
thanks for any advice!

1). Because boolean true is not equal to string "true". So comparison checked == true is always false, and checkbox never gets checked.
Instead try this:
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
if (checked == true) {
document.getElementById("checkbox1zaal1").checked = true;
}
And remember whatever you store in localStorage is always a string, and only a string. That's why when you save something more complex then primitive value (for example some object) make sure to use JSON.stringify on it first.
When you retrieve the value from localStorage you should convert it back to it's corresponding javascript type.
In general load function can also be improved:
function load(){
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
document.getElementById("checkbox1zaal1").checked = checked;
}
2). Another problem will come up once you try to uncheck checkbox. You are not handling it currently, so change save function to this one:
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
localStorage.setItem('checkbox1zaal1', checkbox.checked);
}
Demo: http://jsfiddle.net/Lwxoeyyp/1/

The problem is that you are storing value as "true" in localStorage which is a string format, Now at time of loading the page value is retrieved as string and you are comparing that String "true" with boolean true. This will return false. One small change as
if (checked == "true")
now this should work.

You can also retrieve the status of your checkbox this way:
var selCheck = document.getElementById("checkOne");
selCheck.checked = (localStorage.getItem("34_chkOne")=="true");
Obviously,
"checkOne" is the id of the checkbox.
"34_chkOne" is the name of the local storage variable.
To store the value, you simply use
var selCheck = document.getElementById("checkOne");
localStorage.setItem("34_chkOne", selCheck.checked);
and, as said above, a variable of type string will be stored.

am using this jquery code and is working with me better
$(function() {
var sound_t_s_data = localStorage.getItem("sound_t_s");
if (sound_t_s_data == "yes") {
$("#sound_t").prop('checked', true);
}
else if(sound_t_s_data == "no"){
$("#sound_t").prop('checked', false);
}
});
$("#sound_t").click(function() {
if ($(this).is(":checked")) {
localStorage.setItem("sound_t_s", "yes");
} else {
localStorage.setItem("sound_t_s", "no");
}
});
And if you want to us it in function use like this
//Play Audio
const s_a = new Audio("audio/s_a.mp3");
$( "#s_r" ).click(function() {
if ($('#sound_t').is(':checked')) {
s_a.play()
}
});

Related

Using LocalStorage to store my array of checkbox checked Values and Retrieving it On Page Refresh

I am working on a page with a list of checkbox in my contact form.
What I want to do with my input values is I want to store this on a localStorage key. When I tried to do it, it worked. It was submitted to confirm page. But when I went back to my previous page, the checked input checkboxes were really checked. But when I try to uncheck the checked checkbox, the value is still saved in my localstorage but it went down to the last element of my array.
Here is my html structure:
<input
id='item3'
name='check-item'
value='Item1'
type='checkbox'
/>
<input
id='item3'
name='check-item'
value='Item2'
type='checkbox'
/>
<input
id='item3'
name='check-item'
value='Item3'
type='checkbox'
/>
here are also my javascript codes:
var boxes, arr;
// This function loads the array and then checks the uid of each checkbox
// against it.
function checkBoxes() {
var getArr = loadBoxArray();
$.each($('input[name=check-item]'), function (i, el) {
for(var ctr=0; ctr<getArr.length; ctr++){
if ($(this).val() === getArr[ctr]) {
$('input[value='+getArr[ctr]+']').prop('checked', true);
} else {
$('input[value='+getArr[i]+']').prop('checked', false);
}
}
});
}
// If the localStorage item is available, load it into an array
// otherwise set a default array and save it to localStorage
const loadBoxArray = () =>{
if (localStorage.getItem('boxes')) {
arr = JSON.parse(localStorage.getItem('boxes'));
return arr;
} else {
arr = [0, 2];
saveBoxArray(arr);
return arr;
}
}
// Save the array to localStorage
function saveBoxArray(arr) {
arr = [...new Set(arr)]
localStorage.setItem('boxes', JSON.stringify(arr));
}
// On page load check the boxes found in localStorage
checkBoxes();
// Clicking a checkbox will update the checkbox array which is then saved to localStorage
$('input[name=check-item]').click(function () {
var arr = $.map($('input[name=check-item]:checked'), function (el) {
return $(el).val();
});
saveBoxArray(arr);
});
What could be wrong in my code? I am working on this for almost 4hrs already and I haven't solved this issue.
use while loop, instead of for loop. hope its helps you solve your current issue. thanks!
LocalStorage can only save simple objects. Convert the array to a JSON string first.
Storing Objects in HTML5 localStorage

Django Form Javascript read Boolean field

In my models.py I have
urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje")
And I wish to run a javascript function to change a text field depending on 'True' or 'False' on that Boolean field. Problem is, I can't get the value. When I use document.getElementById('id_urgency').value; I always get 'on', no matter of clickbox check. Why is that? I guess I'm reading the value wrong? Or?
<script type="text/javascript">
function makeReadOnly()
{
var a = document.getElementById('id_urgency').value;
console.log(a);
if (document.getElementById('id_urgency').value == 'True'){
document.getElementById('id_date_days').readOnly = true;
}else if (document.getElementById('id_urgency').value == 'False'){
document.getElementById('id_date_days').readOnly = false;
}
}
document.getElementById('id_urgency').addEventListener('change', makeReadOnly);
This is a part of django form. If I go to 'inspect' on that page, that Checkbox doesn't even have value, why is that?
input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"
By using .value, you get the value attached to that checkbox, not whether the checkbox is checked or not.
You can check if a checkbox is checked with:
var a = document.getElementById('id_urgency').checked;
or as specified by javascripttutorial.net:
To check if the accept checkbox is checked, you use the following
code:
const cb = document.getElementById('accept');
console.log(cb.checked);
(…)
If you get the value attribute of a checkbox, you always get the 'on' string whether the checkbox is checked or not. For example:
const cb = document.getElementById('accept');
console.log(cb.value); // on

Problem changing the value of a checkbox dynamically using JavaScript

I have a checkbox on a form which works fine. When the form s clicked I am trying to change the value to 1, when not clicked the value should be zero. I am filling the field dynamically using JavaScript. The problem is, when I log it in console I get an empty value..
Checkbox field
function checkMark() {
var checkBox = document.getElementById("spouse");
if (checkBox.checked == true){
checkBox.value = '1';
} else {
checkBox.value = 'O';
}
}
var spouse = $('#spouse').val();
console.log(spouse);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">
The reason of your issue is that you're logging just when the page is initially loaded. You have to log the result every time you change the checkbox value.
Also, you can use ternary operator in order to simplify the solution.
function checkMark() {
var checkBox = document.getElementById("spouse");
checkBox.value = checkBox.checked ? '1' : '0';
log();
}
function log(){
var spouse = $('#spouse').val();
console.log(spouse);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="spouse" value="" class="spouse" onclick="checkMark()">
Try calling your function over onChange instead of onClick

jQuery CheckBox Selector .attr('checked) is not working?

I have a checkbox called chkBox1 and i want assign a variable true or false as per the value of selected checkbox.
<input type="checkbox" id="chkBox1">
var chkBox1Val = $('#chkBox1').attr('checked') ? true: false;
The above code is not working. How do i get the value of checkbox checked state and assigned to a variable as true/false?
var chkBox1Val = $('#chkBox1').attr('checked') === 'checked';
Or, if you are using jQuery version greater than 1.6:
var chkBox1Val = $('#chkBox1').prop('checked');
For more info, have a look at the section Attributes vs. Properties of the jQuery .prop() docs.
Use this
var chkBox1Val = $('#chkBox1').is(':checked')
Here's my solution. Hope it helps!
$(document).ready(function(){
var ckbox = $('#chkBox1');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="checkbox" id="chkBox1">

Using javascript to check if an array of check boxes have been selected

So i have a list of check boxes created through unique values of a query. Once i have these values i was to check and make sure the user has checked at least one before being able to submit the form to be exported as an excel document. if they have not checked one box then i was it to send an alert and cancel the submit.
here is my script:
document.getElementById('btnPrint').onclick = function(){
var checkOperator = $('input[name="OperatorName[]"]:checked').length;
if(!checkOperator){
alert('It worked!')
return false;
}
return true;
};
<input type="submit" name="btnSubmit" value="preview" onclick="submitForm('index.php')"/>
<input type="submit" id="btnPrint" name="btnSubmitPrint" value="print" onsubmit="submitForm('exportExcel.php')"/>
what's happening now is that it is still exporting to excel and not showing the alert and canceling.
You are comparing a boolean against a number. Try this instead:
if(checkOperator > 0){
alert('It worked!')
return false;
}
Here's how you would do it with jQuery (since that is a valid tag for your question, and it is automatically cross-browser, and less typing...):
var cnt = 0;
$('#btnPrint').click(function(){
$('input[type=checkbox]').each(function(){
if ( $(this).prop('checked') ) cnt++;
});
if (cnt==0){
alert('Please check a checkbox');
return false;
}
});
jsFiddle Demo
Simply return in your method
return checkOperator !== 0;

Categories