How to keep Checkboxes checked after refresh the page [duplicate] - javascript

hi i am javascript newbie.
I have checkbox that slideDown other input , i want to keep that checkbox checked and the other input showed after refreshing the page if the input checkbox checked
javascript:
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
}
}
this my inputs:
<label for="sitecheck">
<span style="font-weight:bold;">close site+ msg:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">click to activate msg</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="enter closed msg.."/>
i want if checked stay checked.. and wont change after refreshing the page , then when unchecked so back to normal and be unchecked when refreshing the page..
should i use php for making it not change after checking with javascript?
Edited:
Thanks to all for helping
credit goes to : leiyonglin .
The working code for anyone who like to use it:
download first:
https://github.com/carhartl/jquery-cookie
then use this codes working awesome :
JavaScript:
<script type="text/javascript">
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked");
$.cookie("cookieChecked","");
}
}
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').show();
}else{
$("#sitecheck").removeProp("checked");
$('#closedmsg').hide();
}
})
</script>
html inputs:
<label for="sitecheck">
<span style="font-weight:bold;">close site temp:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">close site and add message</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="<?php echo $data['csitemsg']; ?>" />
This working perfect thx again all.

You can use cookie to maintain your data on page refresh by using cookie. I notice you are using JQuery in your code. Here is a JQuery-Cookie plugin which will let you use cookie to manage your data across page refresh.
https://github.com/carhartl/jquery-cookie
Go to Usage section and you will find how to create, read, delete and set expire easily form the plugin.

Set cookies:
Save the checked element in cookieChecked
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
When page onload
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
I use the jquery cookie plugin : https://github.com/carhartl/jquery-cookie

Identify the page refresh event and store the status of check box in cache or local storage. After refresh completes based on the checked status perform your logic

Try this, not use additional plugin:
<script>
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
document.cookie="sitecheck=site_checked";
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
document.cookie="sitecheck=site_unchecked";
}
}
</script>
When document ready:
<script>
$(function(){
var kuki=read_cookie("sitecheck");
if(kuki=="site_checked"){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
}
});
</script>
Read cookies
<script>
function read_cookie(name) {
var name = name + "=";
var kukiAri = document.cookie.split(';');
for(var i=0;i < kukiAri.length;i++) {
var kuki = kukiAri[i];
while (kuki.charAt(0)==' ') kuki = kuki.substring(1,kuki.length);
if (kuki.indexOf(name) == 0)
return kuki.substring(name.length,kuki.length);
}
return null;
};
</script>

Related

I am unable to store the check box state when the page is refreshed in local Storage?

I am unable to store the check box state. I try to store the state in local storage but after page refresh the tick disappears from the checkbox.
<form>
<input type="checkbox" id="checkbox1" onchange = "save();">Tick the check box</input>
</form>
<script>
function save() {
var checkbox = document.getElementById('checkbox1');
localStorage.setItem('check', checkbox.checked);
}
window.onload()=function() {
var checked = JSON.parse(localStorage.getItem('check'));
document.getElementById("checkbox1").checked = checked;
}
<script>
Two changes:
Change window.onload() = to window.onload =.
Remember to call save() whenever the checkbox changes value with .addEventListener("change", save).
//Our checkbox
var checkbox = document.getElementById('checkbox1');
//This function saves the checkbox value:
function save() {
localStorage.setItem('check', checkbox.checked);
}
//This function reloads the checkbox like how it was from localStorage:
window.onload = function() {
var checked = JSON.parse(localStorage.getItem('check'));
checkbox.checked = checked;
}
//Remember to save whenever the checkbox changes:
checkbox.addEventListener("change", save);
<form>
<input type="checkbox" id="checkbox1" onchange = "save();">Tick the check box</input>
</form>
With window.onload(), you call a function, not declare it. Change
window.onload()=function(){
to
window.onload = function() {
And a much better way if you use jQuery:
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Tick the check box</label>
$(function()
{
$("#checkbox1").change(function()
{
localStorage.check = this.checked;
});
var isChecked = localStorage.check ? localStorage.check == "true" : false;
$("#checkbox1").prop("checked", isChecked);
});
jQuery has a function, called .ready. You do not need to parse localStorage.check, since its value isn't an JSON object. Everything in the localStorage are stored as string, localStorage.check == "true" will give you a real boolean value. You also need a default value, false, if the user haven't clicked on the checkbox. <input>text</input> is an invalid syntax. Use <label> if you want "clickable" text.
Edit: for all checkboxes in a form:
<form id="myForm" method="post" action="some.php">
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Tick the check box</label>
<br />
<input type="checkbox" id="checkbox2" />
<label for="checkbox2">Tick the check box</label>
<br />
<input type="checkbox" id="checkbox3" />
<label for="checkbox3">Tick the check box</label>
</form>
$(function()
{
$("#myForm input[type='checkbox']").change(function()
{
localStorage[$(this).attr("id")] = this.checked;
});
$("#myForm input[type='checkbox']").each(function()
{
var val = localStorage[$(this).attr("id")];
var isChecked = val !== undefined ? val == "true" : false;
$(this).prop("checked", isChecked);
});
});
The other solutions to your problem (correcting window.load) seem good (see also the Mozilla docs):
If you want to do JSON.parse() to restore the data, then encoding the data in JSON before storage seems cleaner. So you could do
localStorage.setItem("check", JSON.stringify(checkbox.checked));
instead of
localStorage.setItem('check', checkbox.checked);
If you want persistence just for the browser session (you said "when the page is refreshed"), you can use sessionStorage. This is cleared after the browser ends, but is saved while the browser is active. As localStorage apparently is loaded whenever the browser starts (which can add up for many sites), this persists your data between reloads, but does not clutter the user's computer.

JavaScript if Statement after page been loaded

I have the following if statement:
echo "<a href='searchPage.php?user_query=$crs_sub1&search=search' id='liSpacing'><label id='labelSearch'><input id='checkbox1' type='checkbox' name='checkbox' value='value' checked> $crs_sub1</label></a> <br />";
JavaScript
<Script>
var crs_category1 = document.getElementById("checkbox1").checked;
if (crs_category1 === false){
}else{
document.getElementById("checkbox1").style.visibility = "hidden";
}
</script>
The issue I have is that only checks the input when the page laods. I would want it to be dynamic where after the page as being loaded, once the checkbox is untick, the line goes hidden
The desired effect should occur if the script is inserted directly after the checkbox.
However, it should be noted that the script only checks for the checkboxes value once.
This can be resolved by doing :
<script>
document.getElementById("checkbox1").addEventListener('change', function() {
var crs_category1 = document.getElementById("checkbox1").checked;
if (crs_category1 === false){
} else {
document.getElementById("checkbox1").style.visibility = "hidden";
}
});
</script>
By the way, you can used checked="checked" on a checkbox to make it selected by default, as you wished for in your post. Remember to change the if statement should you do this.
what would be your reference element that you are trying to hide? I mean you can not checked and unchecked if the element is once hidden. so window.onload function should do the work. it has other ways to do it too based on your requirement.

jQuery, how do I call a url by checking a checkbox

I have this:
<span id="social">
Facebook:
<input id="id_connected_to_facebook" type="checkbox" name="connected_to_facebook">
<br>
Twitter:
<input id="id_connected_to_twitter" type="checkbox" name="connected_to_twitter">
<br>
</span>
and with jQuery I would like to call a different URL for all the 4 possible actions (1: check facebook, 2: uncheck facebook, 3: check twitter, 4: uncheck twitter).
How would I do that?
I am not sure what you are going for. If you want to redirect to a page on clicking on the check box you can do this
Specify what url you want to call in your checkbox element using data attribute
<input type="checkbox" data-target="http://www.facebook.com" />
Script is
$(function(){
$("input[type='checkbox']").change(function(){
var item=$(this);
if(item.is(":checked"))
{
window.location.href= item.data("target")
}
});
});
Sample JsFiddle : http://jsfiddle.net/45aZ8/2/
EDIT : If you want to open it in a new window, use window.open method instead of updating the current url
Replace
window.location.href= item.data("target")
with
window.open(item.data("target")
http://www.w3schools.com/jsref/met_win_open.asp
EDIT 3 : Based on comment : If you want to load one url on Checked state and load another url on uncheck, you can do like this
Give 2 data attributes for each checkbox. One for checked state and one for unchecked
Facebook<input type="checkbox" data-target="http://www.facebook.com" data-target-off="http://www.google.com" /> <br/>
Twitter<input type="checkbox" data-target="http://www.twitter.com" data-target-off="http://www.asp.net" /> <br/>
And the script is
$(function(){
$("input[type='checkbox']").change(function(){
var item=$(this);
if(item.is(":checked"))
{
window.open(item.data("target"))
}
else
{
window.open(item.data("target-off"))
}
});
})
Working sample : http://jsfiddle.net/45aZ8/5/
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')) {
if($(this).attr('id') == 'connected_to_facebook') {
// possibility: 1
} else {
// possibility: 3
}
} else {
if($(this).attr('id') == 'connected_to_facebook') {
// possibility: 2
} else {
// possibility: 4
}
}
});
$('#id_connected_to_facebook, #id_connected_to_twitter').click(function(){
$.post('http://target.url', {this.id:this.checked});
});
now you'll get in $_POST either id_connected_to_facebook or id_connected_to_twitter and as a value it would be 1 or 0

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Modal box + checkbox + cookie

I would like to achieve the following:
On homepage load, display modal box
Within modal box, display a form with a single mandatory checkbox
On checking the checkbox, hit submit and close the modal box, proceed to homepage
Remember this checkbox tick preference using a cookie
On a users return to the homepage, if they have checked the checkbox,
the modal box won't display
I've been getting somewhere with this:
http://dev.iceburg.net/jquery/jqModal
In that I can get the modal box displaying on page load, but I can't work out how to get the form to make the checkbox mandatory and close the box. I also don't know where to start when setting a cookie.
Any pointers would be much appreciated.
Thanks
EDIT: to include code:
Index.html - to display modal box on page load
$().ready(function() {
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
setTimeout($('#ex2').jqmShow(),2000);
});
2.html - modal box content loaded via ajax
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
<form action="" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
Load the jquery cookie plugin to allow to set/read cookies: http://plugins.jquery.com/project/cookie
then.. something like this below. Untested, but you get the idea
index.html:
$().ready(function() {
if (!$.cookie('agreed_to_terms'))
{
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
$('#ex2').jqmShow();
}
});
2.html:
$().ready(function()
{
$('#agreeFrm').submit(function(e)
{
e.preventDefault();
if ($(this).find('input[name=checkbox]').is(':checked'))
{
$.cookie('agreed_to_terms', '1', { path: '/', expires: 999999 });
$('#ex2').jqmHide();
}
});
});
<form id="agreeFrm" action="" method="POST" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
I used a JQuery plugin not long ago called SimpleModal
I was very impressed with how easy it was. On the modal I had multiple checkboxes and to carried the values of the checkboxes back to the page the modal was on after a submit button was hit.
All the info and demos are on the SimpleModal homepage
It works, finally!
I was missing the callback when the cookie exists and these tics '' around the value of the cookie.
Here is how it looks like. Please, let me know if there is some obvious mistake.
(many thanks for your support)
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'Proceed'){
$.cookie("agreed_to_terms", '1', { expires : 1, path: '/' }); //set cookie, expires in 365 days
(typeof callback == 'string') ?
window.location.href = callback :
callback();
}
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: 'true', trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
if ($.cookie('agreed_to_terms') == '1'){window.location.href = callback =
callback()
//they already have cookie set
}else{
confirm('About to visit: '+this.href+' !',this.href);
}
return false;
});
});// JavaScript Document

Categories

Resources