How to keep value of check box saved when page reload? - javascript

I am having difficulty figuring out how to keep the toggle button yes or no in localStorage even when pages refresh. I also want to keep checked or unchecked the toggle button. Note: I have also tried to use autocomplete="false" but it's not worked that way as well. Anyone can help me? Many Thanks.
HTML
<h1 id="marker" style="text-align: center; padding-bottom:50px;"></h1>
<label class="label-switch switch-primary">
<input type="checkbox" class="switch switch-bootstrap status" name="status" id="status"
onclick="yesno() ">
JS code
function yesno(){
let status = document.getElementById("status");
if(status.checked == true)
{
localStorage.setItem("isChecked", true);
status.checked = true;
location.reload();
}
if(status.checked == false)
{
localStorage.setItem("isChecked", false);
}
}
marker.innerHTML= localStorage.getItem("isChecked");

Here's a working sandbox with the solution you are looking for.
I left the markup untouched, but changed the function to this:
function yesno() {
let statusEl = document.getElementById("status");
localStorage.setItem("isChecked",JSON.stringify(statusEl.checked));
const marker = document.getElementById("marker");
marker.innerHTML = localStorage.getItem("isChecked");
}
And added the following function to mark the checkbox as checked if needed when the page loads:
function onInit() {
const isChecked = JSON.parse(localStorage.getItem("isChecked"))
document.getElementById("status").checked = isChecked
}

Related

JS way to enable/disable JQ-Chosen select

So I have this dilemma of disabling the select statement with ui-jq="chosen" as its front-end design. Although this is part of a Laravel project, hope someone can help me fix this problem under JS alone.
Using a checkbox to disable/enable the select statement that is under chosen, the disabled attribute doesn't work with it.
<input type="checkbox" name="checkerBox" id="checker" #if ($leave->onProject) checked #endif onclick="selectHider()">
<select name="leave_id" ui-jq="chosen" class="w-full" id="selection"> //options snipped <select>
then for the JS script below
function selectHider() {
var checkBox = document.getElementById("checkerBox");
if (checkBox.checked == true){
document.getElementById("selection").disabled = false;
} else {
document.getElementById("selection").disabled = true;
}
}
Try this:
function selectHider() {
var checkBox = document.getElementById("checkerBox");
//You can set disable default here, depend on your logic
document.getElementById("selection").setAttribute("disabled", "disabled");
if (checkBox.checked == true){
document.getElementById("selection").removeAttribute("disabled");
}
}

ng-checked in a radio button in AngularJS

In my angular application, I am looping through a collection and displaying the records with input type="radio".
<tr ng-repeat="account in vm.pagedAccounts.items"
ng-class="{ 'highlight': (account.rowIsSelected) }"
<td>
<input
ng-model="account.rowIsSelected"
value="{{account}}"
name="selectedAccount"
ng-checked="account.rowIsSelected"
ng-change="vm.selectAccount(account)"
type="radio">
</td>
In my controller, I first set rowIsSelected property to false for all the accounts.
response.data.results.forEach(function(account) {
account.rowIsSelected = false;
});
So, I just make sure whenever account.rowIsSelected is set to something, make that checked.
This is working fine.
But, in the selectAccount function, if a different account is clicked, I want to remove the previous all highlights and highlight the current one.
vm.selectAccount = function (account) {
if (account.rowIsSelected) {
//First set all false
vm.pagedAccounts.items.forEach(function(account) {
account.rowIsSelected = false;
});
var selectedAccount = vm.pagedAccounts.items
.filter(function(x){
return x.id=== account.id;
});
//Then set only that accounts property to true
selectedAccount[0].rowIsSelected = true;
}
But if I click the same row twice, it is no longer checked. I want to keep it checked and highlighted.
How to do it?
Does whatever I am doing seem right?
Please help.
Try this.
vm.selectAccount = function (checkedItem) {
var selectedAccount;
vm.pagedAccounts.items.forEach(function(account) {
if(checkedItem.id == account.id){
selectedAccount = account;
account.rowIsSelected = true;
}else{
account.rowIsSelected = false;
}
});
//Then set only that accounts property to true
selectedAccount[0].rowIsSelected = true;
}
I think you should organize your radio buttons in a bit different way, like it recommends angularjs
Something like:
<tr ng-repeat="account in vm.pagedAccounts.items"
ng-class="{ 'highlight': vm.pagedAccounts.selected === account }">
<td>
<input
ng-model="vm.pagedAccounts.selected"
ng-value="account"
type="radio">
</td>
...
And radio buttons should be automatically selected, when ng-model values is equal to ng-value, so you don't need any specific logic or ng-checked, etc.

Hidden div remain visible in refresh

I have a simple form that will show hidden div when category is selected in a select tag.
What I want is when I refresh the page, the contents is still visible and also the checked items is still there.
here is the sample code
HTML
<select class="form-control" name="food_type1" id="food_type1">
<option selected="selected" disabled="disable" value="0">SELECT</option>
<option value="1">Fruits</option>
<option value="2">Meat</option>
</select>
<div id="food1" style="display: none;">
<input type="checkbox" name="food1[]" value="Mango">Mango <br>
<input type="checkbox" name="food1[]" value="strawberry">Strawberry
</div>
<div id="food2" style="display: none;">
<input type="checkbox" name="food2[]" value="Beef">Beef <br>
<input type="checkbox" name="food2[]" value="Pork">Pork <br>
<input type="checkbox" name="food2[]" value="Chicken">Chicken
</div>
SCRIPT
$(document).ready(function(){
$('#food_type1').on('change', function() {
if ( this.value == '1') {
$("#food1").show();
$("#food2").hide();
}
else if ( this.value == '2') {
$("#food2").show();
$("#food1").hide();
} else {
$("#food1").hide();
$("#food2").hide();
}
});
});
FIDDLE
https://jsfiddle.net/bk2ohogj/
The simplest way would be to use Local storage. I've updated your fiddle, however you will not be able to test the refresh while in JSFiddle, so you will have to try the code locally on your machine.
JSFiddle: https://jsfiddle.net/m0nk3y/bk2ohogj/4/
You will have to create a couple functions to implement it. I kept them as simple as possible, so they may not address all your use cases, but this should help you get closer to what you are trying to do:
JS:
$(document).ready(function(){
var storedItems = [];
//Store selected items
function storeItem(item) {
storedItems.push(item);
localStorage.setItem("storage", storedItems);
}
//Remove item
function removeItem(item) {
var index = storedItems.indexOf(item);
storedItems.splice(index, 1);
}
//Show list according to Dropdown
function showList(type) {
var $food1 = $("#food1");
var $food2 = $("#food2");
localStorage.setItem("list", type);
if ( type == '1') {
$food1.show();
$food2.hide();
} else if ( type == '2') {
$food2.show();
$food1.hide();
} else {
$food1.hide();
$food2.hide();
}
}
//Get list type
if (localStorage.getItem("list")) {
showList(localStorage.getItem("list"));
}
//Get stored items
if (localStorage.getItem("storage")) {
storedItems = localStorage.getItem("storage");
$.each(storedItems, function(i, val) {
$('input[type="checkbox"][value="'+val+'"]').prop("checked", true);
});
}
//Dropdown
$('#food_type1').on('change', function() {
showList(this.value);
});
//Checkbox
$('input[type="checkbox"]').on('change', function() {
var $this = $(this);
if ($this.is(':checked')) {
storeItem(this.val())
} else {
removeItem(this.val());
}
});
});
You'll need a mechanism to remember the states and dynamically set them on page re/load. You can use sessions (if you are using a server language to generate the pages) or cookies in your scripts. It depends on your scenario.
You can store the states on the server in the db. Whenever the state changes, send an update to the back end which will store the state and return the state. You should use this state to populate the form.
You can use HTML5 Local storage on the browser to retain the states. However, ensure you handle this carefully, per user. Whenever the page reloads, read the state from the local storage and populate the form. In case you have security concerns, be aware that users of the browser can see the content of the local storage.

Creating a check and uncheck all function in Angular Js

I have few check boxes which I have been check already using ng-init
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.A='A'" ng-model="model.A" ng-true-value="'A'" ng-false-value="'nope'"/>A
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.A='B'" ng-model="model.B" ng-true-value="'B'" ng-false-value="'nope'"/>B
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-init="model.C='C'" ng-model="model.C" ng-true-value="'C'" ng-false-value="'nope'"/>C
</label>
</div>
What I want is to create a function to make these check boxes check and uncheck when I check a seperate check box, link or a button. Can some one help me?
Its simple as below,
create a link to toggle the checkboxes check status, Here i have created three links
first one is for toggle the checkbox status, second one for uncheck all the checkboxes and last one for check all the checboxes.
toggle check | uncheck all | check all
click on uncheck will be handle like below,
$scope.uncheckAll = function() {
$scope.model.A = false;
$scope.model.B = false;
$scope.model.C = false;
};
assign a value which result in uncheck of the checkboxes.
click on check all will be handle like below,
$scope.checkAll = function() {
$scope.model.A = 'A';
$scope.model.B = 'B';
$scope.model.C = 'C';
};
Assign the initial values that result in check status of the checkboxes.
Toggle check like below, if A unchecked then all gonna uncheck other vice all are gonna check.
$scope.toggleCheck = function() {
if ($scope.model.A == false) {
$scope.checkAll();
} else {
$scope.uncheckAll();
}
};
here is a DEMO
//on button click
var key;
for(key in $scope.model){
if(//checked condition){
$scope.model[key] = key;
}else{
$scope.model[key] = 'nope';
}
}

Checkbox js toggling incorrectly

I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>​
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2

Categories