Save state of DIV element to LocalStorage - javascript

I would like hide/show some div's elements, depends on the checkboxes.
I have checkboxes, state was saved to localStorage but my DIV element after refresh are unsaved (load with default state). jQuery(-mobile).
Many thanks for your help.
<fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
<legend>Some text.</legend>
<div id="checkbox1">
<label>
<input type="checkbox" data-theme="a" name="ligne1" data-iconpos="right" checked="checked" />Ligne 1</label>
</div>
<div id="checkbox2">
<label>
<input type="checkbox" data-theme="a" name="ligne2" data-iconpos="right" checked="checked" />Ligne 2</label>
</div>
<div id="checkbox3">
<label>
<input type="checkbox" data-theme="a" name="ligne3" data-iconpos="right" checked="checked" />Ligne 3</label>
</div>
<fieldset>
$(document).ready(function () {
function getCurrentValue(checkMe) {
return checkMe.is(':checkbox') ? checkMe.prop('checked') : checkMe.val();
}
function checkvalues() {
var original = true;
$(':input').each(function () {
if (getCurrentValue($(this)) !== $(this).data('originalvalue')) {
original = false;
}
});
return original;
}
if (localStorage) {
$(':input').each(function () {
$(this).data('originalvalue', getCurrentValue($(this)));
});
$('#checkbox1').on('change', ':input', function () {
if (checkvalues()) {
$('#ligne1').show();
} else {
$('#ligne1').hide();
}
});
$('#checkbox2').on('change', ':input', function () {
if (checkvalues()) {
$('#ligne2').show();
} else {
$('#ligne2').hide();
}
});
$('#checkbox3').on('change', ':input', function () {
if (checkvalues()) {
$('#ligne3').show();
} else {
$('#ligne3').hide();
}
});
}});
Live example is here.

You need to add the set and get from localStorage in your code.
To set data you need something like this:
// First we setup the data in key/value pairs
var dataContainer = { 'check1':'checked', 'check2':'notchecked'}
// Then save it to localStorage
localStorage.setItem('storedData', JSON.stringify(dataContainer));
And to get data from localStorage:
var dataRetrieved = localStorage.getItem('storedData');
console.log('Local Storage data:', JSON.parse(dataRetrieved))
More info on localStorage MDN Local Storage

Related

Finding Status of Toggle Switch

Extremely new at Javascript and have been stuck on an if/else statement, because I don't know how to find the status of the Toggle switch I created.
if ( ? ? ? myToggle == "True" ? ? ? ) {
do this;
} else {
do this;
}
<label class="switch">
<input type="checkbox" id="myToggle">
<span class="slider round"></span>
</label>
I just want to find the status as to whether or not the toggle has been switched, and then build an if/else statement from there.
Create an EventListener on the checkbox in order to listen for new changes.
Under the EventListener, there'll be an if statement that checks for .checked attribute. If true, it'll print "Checked". If false, it'll print "Not checked".
Example:
var element = document.getElementById("myToggle");
element.addEventListener("change", function (event) {
if (event.target.checked) {
console.log("Checked");
} else {
console.log("Not checked");
}
});
<label class="switch">
<input type="checkbox" id="myToggle">
<span class="slider round"></span>
</label>
You can use the checked property to return the checked state of a checkbox.
if ( document.getElementById("myToggle").checked === true ) {
// do something
} else {
// do something else
}
Look at this :
https://www.w3schools.com/jsref/prop_checkbox_checked.asp
To get the checked status of input use elem.checked
Take a look at https://www.w3schools.com/jsref/prop_checkbox_checked.asp
if (document.getElementById('myToggle').checked) {
console.log('Toggle is checked')
} else {
console.log('Toggle is not checked')
}
if (document.getElementById('myToggle2').checked) {
console.log('Toggle 2 is checked')
} else {
console.log('Toggle 2 is not checked')
}
<label class="switch">
<input type="checkbox" id="myToggle">
<span class="slider round"></span>
</label>
<label class="switch">
<input type="checkbox" id="myToggle2" checked>
<span class="slider round"></span>
</label>
Since you are using a checkbox you can access its .checked property in javascript
first select your element
const element = document.querySelector(".input")
Secondly make a function to check the state
function checkState() {
const checked = element.checked;
if (checked) {
// do things here
} else { // do things here }
}
To check the state of the checkbox you can use the checked property
if (document.getElementById("myToggle").checked){
//do something
}else{
//do something else
}
See
https://www.w3schools.com/jsref/prop_checkbox_checked.asp
You can look for the checked attribute using the document interface and handle it with pure JS.
function isChecked(){
var c = document.getElementById('myToggle');
if (c.checked) {
console.log("checked");
} else {
console.log("not checked");
}
}
<label class="switch">
<input type="checkbox" id="myToggle">
<span class="slider round"></span>
<button onclick="isChecked()">Check and then click here</button>
</label>

Default Select all checkboxes in angularjs

I am creating a app in angularjs. I have problem while showing all checkbox selected when page open.
here is my code:
<div class="check_box">
<input type="checkbox" id="checkbox1" name="checkbox" ng-model="selectedAllStatus" ng-click="checkAllTypes()">
<label for="checkbox1"><span for="checkbox1">All</span></label>
</div>
</li>
<li ng-repeat="customersFlowsList in customersFlows | unique:'type'" ng-init="checkAllTypes()">
<div class="check_box">
<input type="checkbox" id="checkbox1" name="checkbox" ng-model="filter[customersFlowsList.type]">
<label for="checkbox1"><span for="checkbox1">{{customersFlowsList.type | customerType}}</span></label>
</div>
</li>
Here is my js code:
$scope.checkAllStatus = function()
{
console.log($scope.selectedAll)
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.customersFlows, function (customersFlowsList) {
$scope.filterLink[customersFlowsList.linkStatus] = $scope.selectedAll;
});
}
On click of button all checkboxes selected(this is working),but I want when page is open then all checkboxes should be selected.
you can do it in controller before template load
$scope.checkAllStatus = function() {
console.log($scope.selectedAll)
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.customersFlows, function(customersFlowsList) {
$scope.filterLink[customersFlowsList.linkStatus] = $scope.selectedAll;
});
}
$scope.selectedAllStatus = true;
$scope.checkAllStatus()

how to use ng-show with checkboxes

I have tried all the solutions i could find but i am stuck. I have 2 checkboxes, HBO and Marvin. Marvin needs to show a div. HBO needs to show nothing. It works until I need to click the checkbox twice for it to show/hide. usually this would be a $apply() issue but that does not seem to be the case. I believe I am not updating the model correctly. I forgot to mention that the checkboxes need to reset to false when the other is true.
plunker
var ctrl = this;
ctrl.showMeMarvin = function () {
if (ctrl.show === true) {
//$timeout(function () {
ctrl.marvin = false;
ctrl.show = false;
ctrl.hbo = false;
//})
}
else {
//$timeout(function () {
ctrl.marvin = true;
ctrl.show = true;
ctrl.hbo = false;
//})
}
};
ctrl.showMeHBO = function () {
if (ctrl.show === true) {
// $timeout(function () {
ctrl.show = false;
ctrl.hbo = true;
ctrl.marvin = false;
//})
}
else {
//$timeout(function () {
ctrl.marvin = false;
ctrl.hbo = true;
//})
}
};
Just change the div ng-show like this:
<div class="col-xs-12" ng-show="checkedHBO == 1">
And it will work without any additional functions calls.
Edit:
To have it working with the condition to reset the prev selected value you can use this:
<div ng-controller="ShowController as ctrl">
<div class="col-xs-12">
<label for="checkedHBO" class="ts-label">HBO</label>
<input id="checkedHBO" name="mygroup" type="radio" value="hbo" ng-model="checkedHBO" ng-change="checkedMarvin = undefined"/>
<label for="checkedMarvin" class="ts-label">Marvin</label>
<input id="checkedMarvin" name="mygroup" type="radio" value="marvin" ng-model="checkedMarvin" ng-change="checkedHBO = undefined"/>
</div>
<div class="col-xs-12" ng-show="checkedHBO">
<center>
<div class="jumbotron">
DIV 1
</div>
<div class="jumbotron">
DIV 2
</div>
<div class="jumbotron">
DIV 3
</div>
</center>
</div>
</div>
You should be using a radio input instead of checkboxes. http://plnkr.co/edit/hE68w9RKUoFamAWGgRzR?p=preview
<input name="radio" id="checkedHBO" type="radio" ng-model="ctrl.show" ng-value="false" />
<input name="radio" id="checkedMarvin" type="radio" ng-model="ctrl.show" ng-value="true"/>

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Jquery append values to a url as query string

I tried some jquery to append my check box checked values to the url as query string the code is working nice but when I check more than one checkbox the url will like this.....
Localhost:355/searchdatabase/?manufacturer=LG&manufacturer=Samsung&manufacturer=Test
But I need the url Like
Localhost:355/searchdatabase/?manufacturer=LG,Samsung,Test
here is my code
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function (e) {
var data = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
data.push(this.name + '=' + this.value);
}
});
data = data.join('&');
$.post('/ajax-post-url/', data);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + data);
}
});
});
My checkbox list groups code here
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>LG</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Samsung</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Test</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>iron</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>steel</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>copper</label>
</div>
I need Manufacturer as a group and material as another..
You can add all manufacturers to separated array and then add as one field.
var manufacturers = [];
if (this.checked) {
if (this.name === 'manufacturers') {
manufacturers.push(this.value);
} else {
data.push(this.name + '=' + this.value);
}
}
And before data = data.join('&'); add data.push('manufacturers=' + manufacturers.join(','));.

Categories