How to code a proper checkbox that saves changes after refreshing page - javascript

I’m trying to do a simple personal website with checkboxes implemented into it, I’ve never done anything to do with coding ever so I’m super confused on how to put it all together. So far I have a checkbox labeled as purchased, but after I check the box and refresh the page it’s like I never checked the box. I was reading that I need local storage implemented into the code for my changes to save even after refreshing the page. But I have no idea how it should be done and what exactly I need to type in, if anyone could leave what it’s supposed to look like that would be great, thank you genuinely! What I have so far:
<label class="form-control">
<input type="checkbox" name="purchased" />
Purchased
</label>

You can implement a persistent checkbox using local storage like this:
const cb = document.getElementById('checkbox');
//run every time the checkbox is set
cb.addEventListener('input', (e) => {
console.log('changed');
localStorage.setItem('purchased', e.target.checked);
});
//run once on page load, check if it is set in LS if yes then check it
const localPurchasedValue = localStorage.getItem('purchased');
if (localPurchasedValue === 'true') {
cb.checked = true;
}
<label class="form-control">
<input id="checkbox" type="checkbox" name="purchased" />
Purchased
</label>
Note this little preview will not work due to iframe restrictions on this site, but if you copy this into your own file and run with a dev server or some kind you can see it working.

"... but after I check the box and refresh the page it’s like I never checked the box..."
Hi, according comments is necessary to save into some type storage.
Look like this:
let boxes = document.getElementsByClassName('box').length;
function save() {
for(let i = 1; i <= boxes; i++){
var checkbox = document.getElementById(String(i));
localStorage.setItem("checkbox" + String(i), checkbox.checked);
}
}
//for loading
for(let i = 1; i <= boxes; i++){
if(localStorage.length > 0){
var checked = JSON.parse(localStorage.getItem("checkbox" + String(i)));
document.getElementById(String(i)).checked = checked;
}
}
window.addEventListener('change', save);
<input type="checkbox" id="1" class="box">checkbox1</input><br>
<input type="checkbox" id="2" class="box">checkbox2</input><br>
<input type="checkbox" id="3" class="box">checkbox3</input><br>
<input type="checkbox" id="4" class="box">checkbox4</input><br>
<input type="checkbox" id="5" class="box">checkbox5</input><br>
<input type="checkbox" id="6" class="box">checkbox6</input><br>

Related

Having trouble getting inside an .each function that finds checkboxes

I've used similar code earlier in the application and it works, but for some reason, I cannot get anything inside the .each function here to fire.
I have an application where you can check a membership checkbox to apply a 10% credit to the premium of a premise. The number of premises is dynamic, so when you check the membership box, the javascript creates a premise checkbox for each user-created premise on the page. No problem there.
But, I need to find the label for each premise that is checked under the membership box, and my code is failing. The alerts inside that .each do not fire. I've rewritten it to go Div by Div to reach those checkboxes, but I still cannot reach it.
HTML
<div class="form-check creditChecks">
<input class="form-check-input creditCheckInput" type="checkbox" value='4' id="Membership">
<label class="form-check-label" for="Membership">Association Membership</label>
<div class="creditPremiseSelect">
<div class="form-check">
<input class="form-check-input creditPremiseInput" type="checkbox" value='1' id="MembershipcreditPrem1">
<label class="form-check-label" for="MembershipcreditPrem1">Premise #1</label>
</div>
</div>
Javascript to append more premise checkboxes:
//Populate Credit/Debit Premise Selector
function loadSelectPrems(ele){
var firedInput = ele;
var inputID = ele.attr('id');
var thisDiv = firedInput.closest('.creditChecks');
var selector = thisDiv.find('.creditPremiseSelect');
//Empty selector
selector.empty();
//Find all Premises on Policy
$('.premiseList').find('.premise').each(function(index){
var premiseID = $(this).find('.premiseNum').text();
var premNum = index+1;
selector.append($(`
<div class='form-check'>
<input class='form-check-input creditPremiseInput' type='checkbox' value='`+premNum+`' id='`+inputID+`creditPrem`+premNum+`'>
<label class='form-check-label' for='`+inputID+`creditPrem`+premNum+`'>`+premiseID+`</label>
</div>
`))
});
}
JQuery that isn't working as expected:
if($('#Membership').is(':checked')){
doc.text(25, lineCount, 'Association Membership Credit 10% applied to:');
updateLine('s');
alert("Membership checked"); //This alert fires
$(this).closest('.creditChecks').find('.creditPremiseInput').each(function(){
alert("Looking at premises"); //This alert does not fire
if($(this).is(':checked')){
alert("Found checked premise");
var labeltxt = $(this).closest('.creditPremiseSelect').find('.form-check-label').text();
doc.text(30, lineCount, labeltxt);
updateLine('s');
}
});
updateLine('n');
}
I'm going to go out on a limb and say the error is on this line:
$(this).closest('.creditChecks').find('.creditPremiseInput').each...
It appears you are referencing $(this) as being $('#Membership'), but it isn't. Also, as you've assigned a singular ID $('#Membership'), I think you probably just need to access $('.creditChecks') directly in that line.
if ($('#Membership').is(':checked')) {
doc.text(25, lineCount, 'Association Membership Credit 10% applied to:');
updateLine('s');
alert("Membership checked"); //This alert fires
$('.creditChecks').find('.creditPremiseInput').each(function() {
alert("Looking at premises"); //This alert does not fire
if ($(this).is(':checked')) {
alert("Found checked premise");
var labeltxt = $(this).closest('.creditPremiseSelect').find('.form-check-label').text();
doc.text(30, lineCount, labeltxt);
updateLine('s');
}
});
updateLine('n');
}

Input radio elements result always checked

I've searched all the web about it but i couldn't find a solution in javascript without jquery. The problem is the following: I have an entire array of radio elements, which should be checked or unchecked depending on database data. And this is accomplished. Now i have to make the radio button "uncheckable" to change the database data through the form.
I tried to make it in plain javascript as i don't want to think about frontend libraries for the moment.
The html is the following:
<td>
<input class="graphs" name="g4" value="S" defaultvalue="N" checked="true" type="radio">
</td>
<td>
<input class="graphs" name="g5" value="S" defaultvalue="N" type="radio">
The Javascript is the following:
<script type="text/javascript">
window.onload = (function(){
return function(){
var allRadios = document.getElementsByClassName('graphs');
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(this.checked == true){
this.checked = false;
}else{
this.checked = true
}
};
}
}})();
</script>
I've tried to debug and the result is always the same: the first if is executed and always true, even when the element is not checked.
I've tried the same script in jsfiddle and it works right. Is it a problem of my browser?
Thanks in advance.
this.checked == true in else block is not an assignment
If you want a radio to be uncheckable the you can disable it statically, you don't need to use any javascript.
For Unckecked disabled
<input type="radio" name="foo" value="N" disabled>
Four Checked disabled
<input type="radio" name="foo" value="N" checked disabled>

changing checkboxes into animatable buttons with javascript

I'm building a practice app. I've got a working filter system using checkboxes and radio buttons. I need a way to replace them with buttons that I can animate. For my plunk I'll use buttons with text, but then offline I'll replace them with images. Here's a sample of my work:
HTML
<h2>Type</h2>
<label class="btns">
<input type="radio" name="vegMeat" value="" ng-model="type.searchVeg" ng-checked="true">All
</label>
<label class="btns">
<input type="radio" name="vegMeat" value="veg" ng-model="type.searchVeg">Vegetarian
</label>
<label class="btns">
<input type="radio" name="vegMeat" value="meat" ng-model="type.searchVeg">Meat
</label>
</div>
JavaScript
.filter('searchType', function() {
return function(foods, search) {
var filtered = [];
if (!search) {
return foods;
}
angular.forEach(foods, function(food) {
if (angular.lowercase(food.type).indexOf(angular.lowercase(search)) != -1) {
filtered.push(food);
}
});
return filtered;
};
sample plunk
https://plnkr.co/edit/xk1VcCfAsVknyahux4fw?p=preview
PS I know mine is not the most efficient way of doing it, but I'm still a beginner. The buttons are my main concern but if anyone does have suggestions on how to improve the code itself, please feel free to provide an example. This is just a sample of my plunk. My full one has another 5 sets of buttons and many more recipes.

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

Select All checkbox by Javascript or console

I am having 100 Checkboxes on my web page. For testing purposes I want to tick all those boxes, but manually clicking is time consuming. Is there a possible way to get them ticked?
Perhaps a JavaScript or Chrome Console window, anything?
The most direct way would be to grab all your inputs, filter just the checkboxes out, and set the checked property.
var allInputs = document.getElementsByTagName("input");
for (var i = 0, max = allInputs.length; i < max; i++){
if (allInputs[i].type === 'checkbox')
allInputs[i].checked = true;
}
If you happen to be using jQuery—and I'm not saying you should start just to tick all your checkboxes for testing—you could simply do
$("input[type='checkbox']").prop("checked", true);
or as Fabricio points out:
$(":checkbox").prop("checked", true);
Pure JS method, don't use jQuery.. its just silly for something so trivial.
[].forEach.call( document.querySelectorAll('input[type="checkbox"]'),function(el){
el.checked=true;
}
);​
Live Demo
To use it on any webpage you can paste this into the address bar
javascript:[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
then drag that to your bookmarks, and you have a bookmarklet. Just click it whenever you need to use it on a page.
querySelectorAll is your best choice here if you don't want jQuery!
var ele = document.querySelectorAll("input[type=checkbox]");
for(var i=0;i<ele.length;i++){
ele[i].checked = true;
}
//Done.
by using jquery, simple as that
$('input:checkbox').each(function () {
// alert(this);
$(this).attr('checked', true);
});
Or simply use
$('input:checkbox').prop('checked', true);// use the property
OR
$('input:checkbox').attr('checked', true); // by using the attribute
Just paste one of these one-liners to your browser console:
Tick all checkboxes:
document.querySelectorAll('input[type="checkbox"]').forEach(e => e.checked = true);
Untick all checkboxes:
document.querySelectorAll('input[type="checkbox"]').forEach(e => e.checked = false);
This JS code will check all checkboxed in your page:
var a = document.querySelectorAll('input[type="checkbox"]');
for (var i=0; i<a.length; i++)
a[i].checked = true;​
Live demo
All you have to do then is create a bookmarklet with it, say, with this bookmarklet maker, which generates this bookmarklet code:
javascript:var a=document.querySelectorAll('input[type="checkbox"]');for(var i=0;i<a.length;i++)a[i].checked=true;%E2%80%8B
Just add this URI to a bookmark in your bookmark toolbar, then all you have to do is click it whenever you need all the checkboxes in your page to be checked. =]
Multiple Check All & Uncheck All Boxes
All You Need to change is the tag 'name' to change the what its turing ON/OFF
<FORM>
<input type="checkbox" name="item0[]" onclick="CheckAll(this)" />
<input type="checkbox" name="item0[]" value="1" />
<input type="checkbox" name="item0[]" value="2" />
<input type="checkbox" name="item0[]" value="3" />
<br>
<input type="checkbox" name="item1[]" onclick="CheckAll(this)" />
<input type="checkbox" name="item1[]" value="a" />
<input type="checkbox" name="item1[]" value="b" />
<input type="checkbox" name="item1[]" value="c" />
<br>
<input type="checkbox" name="item2" onclick="CheckAll(this)" />
<input type="checkbox" name="item2" value="a1" />
<input type="checkbox" name="item2" value="b2" />
<input type="checkbox" name="item2" value="bc" />
</FORM>
<script>
function CheckAll(x)
{
var allInputs = document.getElementsByName(x.name);
for (var i = 0, max = allInputs.length; i < max; i++)
{
if (allInputs[i].type == 'checkbox')
if (x.checked == true)
allInputs[i].checked = true;
else
allInputs[i].checked = false;
}
}
</script>
I provided answer to this question at Check all Checkboxes in Page via Developer Tools
In short you can do it from dev tools console (F12) by:
$$('input').map(i => i.checked = true)
or
$$('input[type="checkbox"').map(i => i.checked = true)
The following code will toggle all checkboxes. I think this is useful in case you want that feature. If you check a box it will uncheck that box. I know this doesn't answer the question technically but I wanted to put it up here because it's what I use. Thanks for the comment. I hope this answer is better suited to your pallette.
//Select All Checkboxes On Page
allSelects = document.querySelectorAll('input[type="checkbox"]');
for(i=0;i<allSelects.length;i++){
allSelects[i].click();
}
function selectAll(elem)
{
for (i = 0; i < elem.length; i++)
elem[i].checked = true ;
}
On Click of a button call this method and pass the name of the element(checkboxes-they all should be same named).

Categories