Storing checkbox value in local storage - javascript

I have a checkbox whose value $row['uid'] I would like to store in local storage using javascript or jquery. When the user "unchecks" the checkbox, the value should be removed from local storage
This is my html:
<form> Favorites <input type="checkbox" class="favorite" value="'.$row['uid'].' onclick='.fave.add();'"></form>
This is what I have for the local storage in javascript at the moment. I'm not quite sure how I should add and remove the value $row['uid']
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
$(function () {
var data = localStorage.getItem("favorite");
if (data !== null) {
$("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("favorite", $(this).val());
}
else {
localStorage.removeItem("favorite");
}
});
Any and all help is much appreciated!

localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do localStorage.setItem("checkbox_value", true) and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so: $(checkbox).is(':checked') and use a simple if-else clause to pass in true or false. then when you reload your page, on $( document ).ready() you can get the values using localStorage.getItem(key) and use Javascript to set the check boxes values.
This is how i would go about using localStorage to remember check box values.
Hope i helped! Ask me if anything is unclear.

Here's an example to get you headed in the right direction:
var boxes, arr;
// This function loads the array and then checks the uid of each checkbox
// against it.
function checkBoxes() {
arr = loadBoxArray();
$.each($('input[type=checkbox]'), function (i, el) {
if (arr.indexOf(i) > -1) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
}
// If the localStorage item is available, load it into an array
// otherwise set a default array and save it to localStorage
function loadBoxArray() {
if (localStorage.getItem('boxes')) {
arr = loadBoxArray();
} else {
arr = [0, 2];
saveBoxArray(arr);
}
}
// Save the array to localStorage
function saveBoxArray(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[type=checkbox]').click(function () {
var arr = $.map($('input[type=checkbox]:checked'), function (el) {
return $(el).data('uid');
});
saveBoxArray(arr);
});

If you want the check box state to persist after page refresh and if you don't mind using jQuery:
http://jsfiddle.net/9L2Ac/
$(function () {
var data = localStorage.getItem("favorite");
if (data !== null) {
$("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("favorite", $(this).val());
} else {
localStorage.removeItem("favorite");
}
});

Related

If statement never returning true when I first hide the element

$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
var i;
for (i = 0; i < calloutArray.category.length; i++) {
$(this).hide();
if (checkboxName === calloutArray.category[i]) {
$(this).show();
}
}
});
}
});
});
To explain this function it basically listens to see if a checkbox has been clicked and then hides all the callouts on the page.
It then loops through each one of those checkboxes and checks which ones are true on the page. I then create a variable that stores the current checkbox value.
After this I then want to loop through each callout and pull its data from a data attribute.
I then loop through each string in the array and hide the callout no matter what. However if the callout has an array value that is the same as the checkbox value then I need to show it.
This seems to be working without the hide. However I need to hide the callouts if they do not hold the same checked category names which is where I'm running into problems.
The If statement seems to never return true if I have already hidden the callout. So the question is how do I show the callout if the selected checkboxes match one of the callout array strings but hide the callout if the string is not in the callout array.
From what I've understand, the following code is equivalent
$('.checkbox').on('change', function () {
$('.pagination, .callout').hide();
$('.checkbox:checked').each(function () {
var checkboxName = $(this).val();
$('.callout').hide().each(function () {
var calloutArray = $(this).data();
if (calloutArray.category.indexOf(checkboxName) !== -1) {
$(this).show();
}
});
});
});
Merge selectors having common actions(hide())
Use :checked pseudo-selector to select only checked elements
Use hide() on selector and then iterate over it using each()
Use indexOf to check if element is in array
You're showing/hiding your element on each iteration of the loop. That means the result of the last iteration wins, as though you hadn't done the earlier ones at all.
You can just use Array#indexOf to see if the name is in the array, and use the resulting flag to show/hide the callout:
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
E.g.:
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
});
}
});
});
Also note that
if ($(this).prop('checked') === true) {
is quite a long way to write
if (this.checked) {
Similarly, with inputelements, this.value is the same as $(this).val().

Keeping a checkbox checked with local storage but also filter a list on load

Alright, this is/was a 2 part question, I originally posted this function:
$(function () {
var data = localStorage.getItem("filter-by");
if (data !== null) {
$("input[name='filters']").attr("checked", "checked");
}
});
$("input[name='filters']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("filter-by", $(this).val());
} else {
localStorage.removeItem("filters");
}
});
As the start to my re-checking a checkbox after load using local storage. After some trial and error someone was able to help me write this new function:
$("input[name='filters']").click(function () {
var items = localStorage.getItem("filter-by") || [];
var data = this.data('filter-by');
if ($(this).is(":checked")) {
items.push(data);
} else if (items.indexOf(data) >= 0) {
items.splice(items.indexOf(data), 1);
}
if (items.length > 0) {
localStorage.setItem("filter-by", items);
} else {
localStorage.removeItem("filter-by");
}
});
$(function () {
var items = localStorage.getItem("filter-by") || [];
$("input[name='filters']").each(function(index, input) {
var data = $(input).data('filter-by');
if (items.indexOf(data) >= 0) {
$(input).attr('checked', 'checked');
}
});
});
With this function, I'm able to store which checkboxes were checked, but the list does not filter. How can I go about making the list filter on refresh as well, using either of my functions?
I am using an input that looks like this:
<input type="checkbox" name="filters" data-filter-by="Brand A" ng-click="includeBrand('Brand A')" />Brand A
Thanks for the help guys!
Either you have to trigger the click event or you need to call includeBrand(filterString) function for each of the checked items on page load.

In jquery how to put values of check-boxes which are ticked into an array?

I have check-boxes of "Apartment","House" etc. I want to collect the values of these check-boxes into an array and send that array to controller using json. Since I'm new to jquery I don't know how to put those values into an array using jquery ?
<script type="text/javascript">
$(document).ready(function () {
var arr = $("#hiddenroomdetails").val().split(",");
$('input[type=checkbox]').each(function () {
if ($.inArray($(this).val(), arr) > -1) {
$(this).attr("checked", "checked");
}
});
});
</script>
$.getJSON('#Url.Action("testcata", "home")' + '?property=' + selectedvalue +"&chkd="+checkedValues
function (data) {
//code
})
Pretty common way to do it using jQuery is by using map method. For example:
var checkedValues = $('.check:checked').map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/mgzvm2s2/
Lets say if you give these checkboxes a class called "selectbox" and do the following code:
var selected = [];
$('.selectbox').click(function(){
if( $.inArray($(this).val(), selected) > -1 ){
var index = selected.indexOf( $(this).val() );
selected.splice( index, 1 );
}
else {
selected.push( $(this).val() );
}
}
This will fire an event when the checkboxes are clicked. It then checks if the value already exists in the "selected"-array. if it exists, it removes it (checkbox is unchecked). If it doesnt exist (checkbox is checked), it ads it.
Then you can pass on the "selected" array to the json function
You can try this:
$('button').click(function() {
var Arr = [];
$('.check:checked').map(function() {
Arr.push(this.value);
});
alert(Arr);
alert(Arr[0]);
})
Check jsfiddle.net

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

Need help in Javascript onChange event

On change of a dropdown value, I need to confirm whether the user wants to change the value or changed it by mistake.
If user clicks on OK then system should apply the modification, otherwise the value should not change.
As of now I have written code as follows:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
return this;
}
}
here am getting the confirm box but regardless of whether if I press OK or Cancel, the dropdown always shows the new value.
check this fiddle
var drop = document.getElementById("dropdownid");
var selected =drop.options[drop.selectedIndex]; //save selection initially
drop.onclick = function (e){
selected = drop.options[drop.selectedIndex]; // save current selection
}
drop.onchange = function (e){
var a = confirm("Do you want to change");
if (a == false) // no need to check for true
{
selected.selected=true; // if cancel, set the existing selected option
}
}
Please try this:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true)
{
return true;
}
if (a == false)
{
return false;
}
}
You can undo the selection like this:
document.getElementById("dropdownid").onchange = function (){
if (!confirm("Do you want to change")) {
if (typeof this.prevVal=='undefined') {
this.prevVal=this.options[0].value;
for (var i=0;i<this.options.length;i++)
if (this.options[i].defaultSelected)
this.prevVal=this.options[i].value;
}
this.value=this.prevVal;
} else {
this.prevVal=this.value;
}
}
Basically you save in an attribute the previously selected value, and you search for the default value if not changed yet.
try using this code
document.getElementById("dropdownid").onchange = function (eve){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
eve.preventDefault();
}
}

Categories

Resources