Keeping clicked checkboxes state after page refresh - javascript

Users select checkboxes and hit select, the results are displayed, but then checkboxes lose their checked state and that will make users confused what they checked. I am trying to presist the checkboxes state after the page refresh. I am not able to acheive this yet, but I am hopeful its doable. Can someone help me in the right direction?
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/> 
Out-Patient Centers<input name="LocType" type="checkbox" value="Out-Patient"/> 
Facilities<input name="LocType" type="checkbox" value="Facility"/>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit"><span>Search</span></a></div>
$(document).ready(function() {
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('a.searchButton').click(function(){
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
//Now use url variable which has all the checked LocType checkboxes values and jump to url
window.location = url+'&k='+checkboxValues;
});
//Keep the selected checked on page redirect
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
});

not sure if you're still interested in this, but I had the same problem a little while ago, and found this generic piece of JS that persist checkbox states:
// This function reads the cookie and checks/unchecks all elements
// that have been stored inside. It will NOT mess with checkboxes
// whose state has not yet been recorded at all.
function restorePersistedCheckBoxes() {
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
var el = document.getElementById(aPair[0]);
if(el) {
el.checked = aPair[1] == '1';
}
}
}
// This function takes as input an input type="checkbox" element and
// stores its check state in the persistence cookie. It is smart
// enough to add or replace the state as appropriate, and not affect
// the stored state of other checkboxes.
function persistCheckBox(el) {
var found = false;
var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
if(aPair[0] == el.id) {
// State for this checkbox was already present; replace it
aStatus[i] = currentStateFragment;
found = true;
break;
}
}
if(!found) {
// State for this checkbox wasn't present; add it
aStatus.push(currentStateFragment);
}
// Now that the array has our info stored, persist it
setPersistedCheckStatus(aStatus);
}
// This function simply returns the checkbox persistence status as
// an array of strings. "Hides" the fact that the data is stored
// in a cookie.
function getPersistedCheckStatus() {
var stored = getPersistenceCookie();
return stored.split(',');
}
// This function stores an array of strings that represents the
// checkbox persistence status. "Hides" the fact that the data is stored
// in a cookie.
function setPersistedCheckStatus(aStatus) {
setPersistenceCookie(aStatus.join(','));
}
// Retrieve the value of the persistence cookie.
function getPersistenceCookie()
{
// cookies are separated by semicolons
var aCookie = document.cookie.split('; ');
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split('=');
if ('JS_PERSISTENCE_COOKIE' == aCrumb[0])
return unescape(aCrumb[1]);
}
return ''; // cookie does not exist
}
// Sets the value of the persistence cookie.
// Does not affect other cookies that may be present.
function setPersistenceCookie(sValue) {
document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
}
// Removes the persistence cookie.
function clearPersistenceCookie() {
document.cookie = 'JS_PERSISTENCE_COOKIE=' +
';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
}
Just make sure your checkboxes have an onChange= persistCheckBox(this); attached to them
eg.
<label for= "LocType">User Preference</label>
<input name= "LocType" type= "checkbox" onChange= persistCheckBox(this);"/>
And also an onLoad in your opening body tag:
<body onload="restorePersistedCheckBoxes();">

I would be more inclined to go with HTML5 web storage (faster and more secure) but cookies would also do the job. Here is a link to some samples using HTML5 http://www.w3schools.com/html5/html5_webstorage.asp

Related

LocalStorage and adding li to list

I'm trying to make a small script that allows for a little notes section. This section would have an input box that allows for adding elements to the list; which will be saved in localStorage so they are not lost when I refresh or close the browser. The code I have is as follows (it's all done through JS even the html, but ignore that.)
var notes = [];
var listthings = "<h2 id=\"titlething\">Notes</h2>" +
"<ul id=\"listing\">" +
"</ul>"
"<input type=\"text\" name=\"item\" id=\"textfield\">" +
"<input type=\"submit\" id=\"submitthing\" value=\"Submit\">";
JSON.parse(localStorage.getItem('notes')) || [].forEach( function (note) {
"<li id=\"listitem\">" + notes + "</li>";
})
$('#submitthing').click(function() {
notes.push($('#textfield').val());
});
localStorage.setItem('notes', JSON.stringify(notes));
Also, how would I go about appending the latest added li between the opening and closing tag? Obviously I'd usually do it using jQuery, but this is puzzling me a little. However, only the 'Notes' loads at the top, any ideas?
Your approach is way off the mark. You don't need JSON at all (this just confuses things) and you don't need to manually create HTML.
Also, you can use an array to store the notes, but since localStorage is the storage area, so an array is redundant. Additionally, without using an array, you don't need JSON. The entire problem becomes much easier to solve.
Unfortunately, the following won't run here in this snippet editor, due to security issues, but it would do what you are asking. This fiddle shows it working: https://jsfiddle.net/Lqjwbn1r/14/
// Upon the page being ready:
window.addEventListener("DOMContentLoaded", function(){
// Get a reference to the empty <ul> element on the page
var list = document.getElementById("notes");
// Loop through localStorage
for (var i = 0; i < localStorage.length; i++){
// Make sure that we only read the notes from local storage
if(localStorage.key(i).indexOf("note") !== -1){
// For each item, create a new <li> element
var item = document.createElement("li");
// Populate the <li> with the contents of the current
// localStorage item's value
item.textContent = localStorage.getItem(localStorage.key(i));
// Append the <li> to the page's <ul>
list.appendChild(item);
}
}
// Get references to the button and input
var btn = document.getElementById("btnSave");
var note = document.getElementById("txtNote");
// Store a note count:
var noteCount = 1;
// When the button is clicked...
btn.addEventListener("click", function(){
// Get the value of the input
var noteVal = note.value;
// As long as the value isn't an empty string...
if(noteVal.trim() !== ""){
// Create the note in localStorage using the
// note counter so that each stored item gets
// a unique key
localStorage.setItem("note" + noteCount, noteVal);
// Create a new <li>
var lstItem = document.createElement("li");
// Set the content of the <li>
lstItem.textContent = noteVal;
// Append the <li> to the <ul>
list.appendChild(lstItem);
// Bump up the note counter
noteCount++;
}
});
});
<input type=text id=txtNote><input type=button value=Save id=btnSave>
<ul id=notes></ul>
This is how I would approach it using jquery. but depens how complex this should be. this is just simple demo.
<input type="text" id="note" />
<button id="add">add note</button>
<ul id="notes"></ul>
javascript and jquery
function addNote(){
var data = localStorage.getItem("notes")
var notes = null;
if(data != null)
{
notes = JSON.parse(data);
}
if(notes == null){
notes = [];
}
notes.push($("#note").val());
localStorage.setItem("notes", JSON.stringify(notes));
refreshNotes();
}
function refreshNotes(){
var notesElement =$("#notes");
notesElement.empty();
var notes = JSON.parse(localStorage.getItem("notes"));
for(var i = 0; i< notes.length; i++){
var note = notes[i];
notesElement.append("<li>"+note+"</li>");
}
}
$(function(){
refreshNotes();
$("#add").click(function(){
addNote();
});
})
example:
http://codepen.io/xszaboj/pen/dOXEey?editors=1010

Value and Focus() not working on dynamically created inputs

I'm trying to create something to refresh the list of dates to all users every 30 seconds.
I dynamically create a table with the list of dates in my database using AJAX, the thing is that the refresh removes what the user was writing in the moment of the refresh so I'm saving what the user writes in javascript global variables, calling the refresh function, then filling the inputs with the information in the variables and focusing the input the user was on.
The thing is the inputs aren't filled nor focused.
this is my relevant code here:
var identificacionc = "";
var nombresc = "";
var apellidosc = "";
var telefonoc = "";
var posicionc = 0;
var ladoc = 0;
//This is called on input onfocus to record the id
function recuerdo(posicion, lado)
{
posicionc = posicion;
ladoc = lado;
}
function actualizar()
{
//This line is not relevant
listaragenda();
if (document.getElementById("datepicker").value != "")
{
//put the info in the global variables and it works even if they're dynamically created
identificacionc = document.getElementById("txtidentificacion" + posicionc).value;
nombresc = document.getElementById("txtnombres" + posicionc).value;
apellidosc = document.getElementById("txtapellidos" + posicionc).value;
telefonoc = document.getElementById("txttelefono" + posicionc).value;
//Here is where I call the function to refresh dates
listarcitas();
}
}
function listarcitas()
{
var objAjax = crearObjeto();
var fecha = document.getElementById("datepicker").value;
objAjax.open("POST", "clases/listarcitas.php", true);
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
objAjax.onreadystatechange = function()
{
if (objAjax.readyState == 4 && objAjax.status == 200)
{
document.getElementById("citaslistadas").innerHTML = objAjax.responseText;
//Checks if any global variable is not empty to start to fill them with the info
//nothing inside this If works
//posicionc and ladoc have the correct values
if (identificacionc != "")
{
document.getElementById("txtidentificacion" + posicionc).value = identificacionc;
document.getElementById("txtnombres" + posicionc).value = nombresc;
document.getElementById("txtapellidos" + posicionc).value = apellidosc;
document.getElementById("txttelefono" + posicionc).value = telefonoc;
if (ladoc == 1)
{
document.getElementById("txtidentificacion" + posicionc).focus();
}
else if (ladoc == 2)
{
document.getElementById("txtnombres" + posicionc).focus();
}
else if (ladoc == 3)
{
document.getElementById("txtapellidos" + posicionc).focus();
}
else if (ladoc == 4)
{
document.getElementById("txttelefono" + posicionc).focus();
}
}
}
}
objAjax.send("fecha=" + fecha);
}
//the interval every 30s
window.setInterval("actualizar()", 30000);
Everything retrieved from AJAX works fine everything is listed, even in the web browser console I make alerts of the variables, set the values and focus the dynamically created inputs, everything works fine.
But why this is not working in the code?
Thanks in advance

Checking if user has unsaved data in JQuery?

I have the following code...
var leave_page_confirm=false;
if ($(':input.common_class').val().length !== 0) {
var leave_page_confirm=true;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (leave_page_confirm) {
return "You have unsaved information on the page.";
}
}
I'm trying to see if any inputs on the page have value. If they don't then you can leave the page without a message. If they do, then there is a message you asking if you would like to leave the page. All of the inputs on my page have a common class.
Some information about the logic I have followed:
This code doesn't save anything, if you need to store some information just with JS, so on the client computer and this will depend on the cache, you can use the cookie(the information are temporary since rely on cookies that can be deleted, so maybe you can store the unsaved values to wait the user to submit them).
The first snippet is based on the idea that the inputs will not be cleared once you save the information(they will keep the information), this means that js checks if the user makes any change to them (can be smarter, maybe check if the value is really different from the beginning one) and set var to true/false, once the user leaves the page then var is checked.
The second script is based on the idea that the inputs are part of a form or something like this, so once it get submitted the inputs will be cleared.
if the user leaves the page the code check if the are any non-empty (saved or not) value.
To sum up:
the first checks if any change has been made to the input
the second one check if the input contains a value
I don't understand the unsaved data: unsaved data or empty values? I mean if a user save a non empty value and then clean the input?
This is what I thought: basically every time the input change it sets the saved var to false and once you hit the button save (or every other logic) it sets the value to true, otherwise once you unload the page the script check the var to see if it is true or false
HTML:
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<button class='save'>Save</button>
JQUERY
var saved= true;
window.onbeforeunload = function () {
if (!saved) {
return 'Would you like to save?';
}
};
$('.test').on('input', function(){
saved=false;
});
$('.save').click(function(){
saved=true;
});
If you just need to check for the input value:
window.onbeforeunload = function () {
var saved= true;
$('.test').val(function(e,v){
//This check if the value is not empty
//if you want any kind of value use if(v)
if(v.trim()!=""){
saved=false;
return;
}
});
if(!saved)
return 'Would you like to save?';
};
You can achive this even with pure js:
window.onbeforeunload = function () {
var saved= true,
items= document.getElementsByClassName('test'),
count= items.length;
for(i=0;i<count;i++){
if(items[i].value!=""){ //if(items[i].value)
saved=false;
break;
}
};
if(!saved)
return 'Would you like to save?';
};
EDIT COOKIE PART - FIXED - WORKS
$(document).ready(function() {
var cookieVal = getCookie('formValue');
if(cookieVal){
var list=$.parseJSON(cookieVal);
$('.test').each(function(){
if($(this).attr('name') in list)
$(this).val(list[$(this).attr('name')]);
});
document.cookie = 'formValue=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
});
window.onbeforeunload = function () {
var saved= true;
$('.test').each(function(){
if($(this).val().trim()!=""){
saved=false;
return;
}
});
if(!saved){
var itemObj= new Object,
d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000));
var expires = "expires="+d.toUTCString();
$('.test').val(function(e,v){
if($(this).attr('name'))
itemObj[$(this).attr('name')]=v;
});
itemObj=JSON.stringify(itemObj);
document.cookie = 'formValue=' + itemObj + "; " + expires;
return 'Would you like to save?';
}
};
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Since you are using jQuery already use each.
var leave_page_confirm = true;
$('.common_class').each(function(){
if($(this).val().length == 0)
leave_page_confirm = false
});
Also check for false if any of them are false it will always return false instead of worrying about checking every one and setting true or false. It will always be false for 1 empty.
One crude way
var leave_page_confirm=false;
$('input').each(
function(){
if($(this).val()){
leave_page_confirm = true;
}
});
try this
var changesSaved =true;
function hasPendingChanges()
{
changesSaved=$(':input.common_class').val().length == 0;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (!changesSaved) {
return "You have unsaved information on the page.";
}
}
I generally use change event to track any of the input has changes as,
var leave_page_confirm = false;
$(function() {
$(':input.common_class').change(function(){
leave_page_confirm = true;
if(!leave_page_confirm)
window.onbeforeunload = save_data_check;
});
});
function save_data_check(){
return "You have unsaved information on the page.";
}

Javascript - Conditionally add checkbox to php page if cookie exists

I have some Javascript that adds some disclaimer text and a confirmation CheckBox, just before a submit button on a PHP/WordPress page. What I'd like to happen is the script checks for the existence of a cookie. If cookie doesn't exist (or has expired), then to add the disclaimer text, the checkbox and force the user to click the Checkbox before proceeding. But once done, a cookie is written so that the next time the script runs, if bypasses the disclaimer text, checkbox and just allows the user to hit 'submit'.
So, something like:
if cookie-exists {
// straight to submit part of the code
} else {
// show disclaimer and checkbox
// Only allow user to hit submit if checkbox is ticked
// Set the cookie with an expire of a day
}
I can see an answer on setting / reading a cookie here > How do I create and read a value from cookie?
But I'm just struggling to get it into the code snippet below.
Any pointers or help would be greatly appreciated. Thanks.
Code snippet follows:
function add_listing_select_cb()
{
?>
<script type="text/javascript">
jQuery(document).ready(function ($){
var checkbox_cont = '<br><input type="checkbox" name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
Have you tried something similar to this?
function add_listing_select_cb()
{
?>
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
jQuery(document).ready(function ($){
if (getCookie("anything")!==true){
var checkbox_cont = '<br><input type="checkbox" **required** name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
}
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}

add values to textbox history without submitting the form using javascript or Jquery

Hello friends I have a <input type="text" id="tempID" /> element in my form
I also have an <input type="button" onclick="doSomething()" /> element in my form.
I want to add the text box value to textbox history when user clicks on the button.
I am processing the request using Jquery ajax. So I have to do it with javascript or Jquery.
Is this possible to add values to the history of particular <input type="text" /> element using javascript/Jquery..??
Here is how you can do it using HTML5 LocalStorage
$( "#tempID" ).autocomplete({
source: function( req, resp ) {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
resp( data );
}
});
$('#tempID').on('blur', function() {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
if($.trim(this.value).length > 0)
data.push(this.value);
localStorage.setItem('custom_history', JSON.stringify(data));
});
What I am doing is Setting the value into HTML5 Local storage when users moves away from the input field, clicks somewhere else.
Then retrieving that and setting that as source for jQuery UI auto complete.
Here is a working fiddle http://jsfiddle.net/joycse06/EBduF/173/
Enter some value. Click somewhere else. Click back again and add other values. The refresh the fiddle and start typing one of those and auto complete will show up.
UPDATE
Based on his comments and later chat the final code he need is this, I am pasting in if it might someone else later
// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
localStorage.setItem('custom_history','');
$( "#test" ).autocomplete({
source: function( req, resp ) {
var term = req.term;
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var intRegex = /^\d+$/;
data = $.map(data,function(val){
if(intRegex.test(val)){
if(val.indexOf(term) != -1)
return val;
else
return null;
}
else
return null;
});
resp( data );
}
});
$('#save').on('click', function() {
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var value = $.trim($('#test').val());
if(value.length > 0){
if($.inArray(value,data) != -1){
//alert('Duplicate');
return;
}
}
data.push(value);
localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
You can use localStorage like following:
var arr = [];
$('input#tempID').on('click', function() {
arr.push(this.value);
localStorage.setItem('history', JSON.stringify(arr)); // set item to localStorage
});
To retrieve that value try,
var temp = localStorage.getItem('history');
if(retarr) { // checking that data it stored in localStorage or not, if not exists temp = null
var allHistories = JSON.parse(temp); // now you have history
console.log(allHistories);
}
I think you need something like autocomplete

Categories

Resources