Retrieve the previously checked checkboxes on page refresh using localStorage - javascript

I have an html code where the checkboxes are checked and onclick of a button the values of checkboxes are sent accross a function. When the user checks a checkbbox the corresponding chidren checkboxes are also checked. If i refresh the page I want to retrieve the previously checked checkboxes. I tried using localStorage to store the checkbox values .
localStorage.setItem("check", check);
Then in another function tried to retrieve it by doing
localStorage.getItem("check");
if(check){
$("input[name='favorites']").attr("checked", "checked");
$(check)
.closest('li')
.find('input:checkbox')
.prop('checked', $(this).prop('checked') );
}
But this does not work . I need to retrieve only the checkboxes which were checked previously on page refresh.
My complete code with demo
html
<ul class="test_ex">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref">Fruits</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Apple </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Orange </a>
</li>
</ul>
<ul class="test_ex_sample">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref">Birds</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Peacock </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Parrot </a>
</li>
</ul>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref"> Food </a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Bread </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<input type="button" id="testB" value="OK" />
javascript
$(function() {
// Clicking on an <input:checkbox> should check any children checkboxes automatically
$('input:checkbox').change( fnTest );
// Clicking the OK button should run submit(), pop up displays all checked boxes
$('#testB').click( submit );
});
function fnTest(check) {
// Set all child checkboxes to the same value
$(check)
.closest('li')
.find('input:checkbox')
.prop('checked', $(this).prop('checked') );
}
function submit(check) {
// When you click OK, dipslay the label for each checkbox
var checked = [];
$('input:checkbox:checked').each(function() {
checked.push( $(this).next('a').text() );
});
alert("You have selected:\n\n - " + checked.join("\n - ") );
}
Updated Fiddle

Try changing this code and see if it works for you:
$(function() {
// Clicking on an <input:checkbox> should check any children checkboxes automatically
$('.ref').each(function(){
var $t = $(this);
$t.siblings('input').attr('data-name',$t.text());
});
$('input:checkbox').change( fnTest );
// Clicking the OK button should run submit(), pop up displays all checked boxes
$('#testB').click( submit );
display();
});
function fnTest(e) {
// Set all child checkboxes to the same value
$(this)
.closest('li')
.find('input:checkbox')
.prop('checked', $(this).prop('checked') );
}
function submit(check) {
// When you click OK, dipslay the label for each checkbox
var checked = [];
$('input:checked').each(function() {
checked.push( $(this).attr('data-name'));
});
alert("You have selected:\n\n - " + checked.join("\n - ") );
localStorage.setItem("prevChecked",checked.join('|'));
}
function display(){
var test=localStorage.getItem("prevChecked");
alert(test);
var results = test.split('|');
for (var r=0, len=results.length; r<len; r++ ) {
$('input[data-name="'+results[r]+'"]').prop('checked', true);
}
}
UPDATED
See this fiddle:
http://jsfiddle.net/3a050r6r/6/

Assign the localStorage to a variable while doing a get like this
var check = localStorage.getItem("check");
Edited :
$(function() {
// Clicking on an <input:checkbox> should check any children checkboxes automatically
$('input:checkbox').change( fnTest );
// Clicking the OK button should run submit(), pop up displays all checked boxes
$('#testB').click( submit );
display();
});
function fnTest(e) {
// Set all child checkboxes to the same value
alert($(this).attr("id"));
localStorage.setItem("prevChecked",$(this).attr("id"));
localStorage.setItem("checkedState",$(this).prop('checked'));
$(this)
.closest('li')
.find('input:checkbox')
.prop('checked', $(this).prop('checked') );
}
function submit(check) {
// When you click OK, dipslay the label for each checkbox
var checked = [];
$('input:checkbox:checked').each(function() {
//localStorage.setItem("prevChecked",check);
checked.push( $(this).next('a').text() );
});
alert("You have selected:\n\n - " + checked.join("\n - ") );
}
function display(){
if(localStorage.getItem("checkedState")!="false")
{
var test=localStorage.getItem("prevChecked");
alert(test);
alert($("#"+test).closest('li').html());
$("#"+test).closest('li')
.find('input:checkbox')
.prop('checked', localStorage.getItem("checkedState") );
}
}
Link to your updated fiddle :
http://jsfiddle.net/3a050r6r/36/

Related

Javascript click function only work once

I have a dropdown menu with a submit function that executes, if any children from the dropdown is clicked.
Now I want to prevent the submit function to a special li element, because there should be insert a tracking id in a popup iFrame.
With the following code it works so far on the first dropdown menu and prevent the submit function, but it wont work on all following dropdown's.
Maybe someone has a short solution for me?
<script type="text/javascript">
$(document).ready(function() {
$('.track').click(function(){
stopPropagation();
});
$('.dropdown li').click(function() {
document.getElementById('opt').value = $(this).data('value');
$('#options').submit();
});
$("#options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
});
</script>
<form name="" action="" method="post" id="options">
<input type="hidden" name="update" id="opt" value="">
<div id="item-select-option">
<div class="dropdown">
Options <span class="caret"></span>
<ul id="selector" class="dropdown-menu pull-right" role="menu">
<li data-value="paid">paid</li>
<li data-value="shipped">shipped</li>
<li class="track">track</li>
</ul>
</div>
</div>
</form>
Problem: You've several elements with the id track/options when the id attribute should be unique in same document, so when you attach event to the id just the first element with this id that will be attached.
Suggested solution :
Use class instead of id's, like :
<form name="" action="" method="post" class="options">
.....
<li class="track">
track
</li>
</form>
Then you js should be like :
$('.track').click(function(event){
event.stopPropagation();
});
$(".options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
NOTE : The event should be present in anonymous function function(event).
Hope this helps.

Add javascript var to href

I have dropdown with different links, before that i have 2 radio buttons where you could select "mode".
<div class="radio">
<label><input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label><input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://example.com/index.php?mode=">Site1</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site2</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site3</a></li>
</ul>
</div>
And i use this code snippet to detect what mode is selcted and add it to var mode:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
});
});
What i want to do is to add javascript var $mode to href tags.
href="http://example.com/index.php?mode={$mode}
How could i accomplish this ?
I think only way would be to do this with some javascript function ?
Its not possible to just "print" var to href ?
JSFIDDLE: https://jsfiddle.net/DTcHh/18683/
Use data-* attribute to keep static href value to be used later. .change() will trigger change event initially to set the value of href attributes.
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function() {
var mode = myRadio.filter(':checked').val();
$('ul.dropdown-menu a').prop('href', function() {
return this.getAttribute('data-href') + mode;
})
}).change();
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label>
<input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://site1.com/index.php?mode=" data-href="http://site1.com/index.php?mode=">Site1</a>
</li>
<li><a target="_blank" href="http://site2.com/index.php?mode=" data-href="http://site2.com/index.php?mode=">Site2</a>
</li>
<li><a target="_blank" href="http://site3.com/index.php?mode=" data-href="http://site3.com/index.php?mode=">Site3</a>
</li>
</ul>
</div>
Fiddle here
Check this fiddle I've modified for you: https://jsfiddle.net/so2fw1o4/1/
Add this to your myRadio.on('change', function
//here change the urls
$('.dropdown-menu a').each(function(){
$(this).attr('href', $(this).data('url') + mode)
})
And you will need to add data attribute to each link to store initial link
<a target="_blank" data-url="http://site. com/index.php?mode=" href="http://site. com/index.php?mode=">Site1</a>
Try this :-
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
$("ul.dropdown-menu li a").each(function(){
$(this).attr('href',$(this).attr('href').split('?')[0] + "?mode=" + mode);
});
}).change(); //trigger on page load
});
DEMO
Although you already have some answers here, I figured I would post another alternative (not necessarily any better).
You could add a class to each link, handle their click events, and set the new window's location yourself to achieve a similar effect.
The following is a code snippet modifying the jQuery in your fiddle:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
var mode = myRadio.filter(':checked').val(); // Initial setting
myRadio.on('change', function () {
mode=myRadio.filter(':checked').val();
});
$('.mode-link').click(function(e) {
e.preventDefault(); //stop the click action
// Check if the mode has been set
if (mode) {
// Create the href value
var newHref = $(this).attr('href') + mode;
// Open the new tab/window with the correct href value
window.open(
newHref,
'_blank'
);
}
});
});
I simply added the mode-link class to each a element in the dropdown, stored the radio button value change in a new variable mode, added the click event handler, and finally handled the click event to create the new href value and open a new tab/window with that location.
If you didn't want the new tab/window you could simply set location.href = newHref but this wouldn't mimic the new tab/window opening, hence why I use window.open().
I have a modified sample here: JSFiddle

when i close the modal, checked inputs became unchecked

i use input with checkbox type to narrow my search result;
problem is i put the checkboxes in to the modal and when i checked many of them and close the modal the checked inputs become unchecked .
and i want every time that i open the modal input checked been checked.
var filterTemps = [
"partial/uicomponent/mdlFilters/mdl.estateType.filter.html",
];
$scope.showReleventMdl = function(num){
var filtersModal = $modal({
backdrop:true,
placement:'top',
templateUrl : filterTemps[num],
controller : 'filterCtrl',
show: false
});
filtersModal.$promise.then(filtersModal.show);
};
<!-- trigger the function for call modal -->
<ul class="nav navbar-nav">
<li>
</li>
...
</ul>
--------------------------------------------------
<!-- my Modal Template -->
<div class="modal-body">
<ul class="filterList">
<li class="filterListItem half" ng-repeat="item in string.pages.mainPage.estateTypes">
<input id="estateType{{$index}}" ng-click="checked(item)" type="checkbox" class="filterCheck">
<label for="estateType{{$index}}" ng-bind="item"></label>
</li>
</ul>
</div>
i want to know is there any way to store checked inputs and bring them back in checked state with modal ?
TNKS a lot
You are not setting any values to a $scope object. Try this...
<div class="modal-body">
<ul class="filterList">
<li class="filterListItem half" ng-repeat="item in string.pages.mainPage.estateTypes">
<input id="estateType{{$index}}" type="checkbox" ng-model="checkbox[$index].checked" class="filterCheck">
<label for="estateType{{$index}}" ng-bind="item"></label>
</li>
</ul>
</div>
Then, in your controller, you can set up the $scope object for your checkbox values.
$scope.checkbox = {};

JQuery conflict (maybe?) Hide/Show Div based on Radio Box

This is driving me crazy. I have tried every different ways to do this. Trying to show/hive a div based on a radio box selection. Below is my code into my main.js :
$("input[name='payment_method']").click(function () {
if ($(this).attr("id") == "payment_method_cod") {
$("#checkout_insurance").show();
} else {
$("#checkout_insurance").hide();
}
});
HTML:
<div id="checkout_insurance">
<h2>Checkout with Insurance</h2>
</div>
<div id="payment" class="woocommerce-checkout-payment">
<ul class="payment_methods methods">
<li class="payment_method_cod">
<input id="payment_method_cod" type="radio" class="input-radio" name="payment_method" value="cod" data-order_button_text="" checked="checked">
<label for="payment_method_cod">
...
</li>
<li class="payment_method_firstdata">
<input id="payment_method_firstdata" type="radio" class="input-radio" name="payment_method" value="firstdata" data-order_button_text="">
<label for="payment_method_firstdata">
....
</li>
</ul>
</div>
I cant get to work. If I place another cdn of the jQuery on the footer, the function works, however messes up a lot of other stuff. jQuery is being loaded on the header. I am current using jQuery 1.11.3.
Any help will be appreciated.
Thank you!
Use :checked selector to check if the radio element with id payment_method_cod is checked or not.
$('#payment_method_cod:checked') will return true/false based on the condition if the radio button is checked or not and toggle it, when true, the element #checkout_insurance will be shown.
Assuming the id's used in the code are unique.
Demo
$(document).on('change', "input[name='payment_method']", function() {
$("#checkout_insurance").toggle($('#payment_method_cod').is(':checked'));
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="checkout_insurance">
<h2>Checkout with Insurance</h2>
</div>
<div id="payment" class="woocommerce-checkout-payment">
<ul class="payment_methods methods">
<li class="payment_method_cod">
<input id="payment_method_cod" type="radio" class="input-radio" name="payment_method" value="cod" data-order_button_text="" checked="checked">
<label for="payment_method_cod">Payment</label>
...
</li>
<li class="payment_method_firstdata">
<input id="payment_method_firstdata" type="radio" class="input-radio" name="payment_method" value="firstdata" data-order_button_text="">
<label for="payment_method_firstdata">FirstData</label>
....
</li>
</ul>
</div>
$("input[name='payment_method']").change(function () {
if ($(this).attr("id") == "payment_method_cod" && $(this).is(':checked')) {
alert('show');
} else {
alert('hide');
}
});
Please use .change() on checkbox use .click() on button.
Try this approach this will select change event on checkbox and check if the id of the checkbox is payment_method_cod it will then show or hide depending on checked property
demo
Changing your code a bit :
$("input[name='payment_method']").click(function () {
var _this = $(this);
if (_this.val() == "cod") {
$("#checkout_insurance").show();
} else {
$("#checkout_insurance").hide();
}
});

Couldn't get the binded values into the list

<div id="list1" class="dropdown-check-list"> <span class="anchor">Select State</span>
<ul class="items" data-bind="foreach:carTypes" onchange="GetSelectedValut1()">
<li>
<label>
<input id="items1" type="checkBox" /><span id="vv1" data-bind="text:text,value:text"></span>
</label>
</li>
</ul>
</div>
Want all the values of the cartypes when i check the box. geting only one (top most one) value here.
Here is my javascript code:
function GetSelectedValut1() {
if (document.getElementById('items1').checked) {
var list_value = document.getElementById("vv1").value;
document.getElementById("vall1").innerHTML = list_value;
} else document.getElementById("vall1").innerHTML = "";
}
want all the values of the cartypes when i check the box. geting only one(top most one) value here. my event to get the values is it sufficient here.

Categories

Resources