Checking if user has unsaved data in JQuery? - javascript

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.";
}

Related

how to manipulate cookie with js

here this code just stores te options and atlast it produces the result from adio buttons. i want it inted of radio button use of textbox or input field. so what should be changed?
<script language="JavaScript">
var timer,timecounter=0
function readCookie(name)
{
var result=null;
var myCookie=document.cookie+";";
var searchName=name+"=";
var start=myCookie.indexOf(searchName);
var end;
if(start!=-1)
{
start+=searchName.length;
end=myCookie.indexOf(";",start);
result=myCookie.substring(start,end);
}
return result;
}
function writeCookie(name)
{
var expDate=new Date();
var day=1*24*60*60;
expDate.setTime(expDate.getTime()+day);
document.cookie=name+"="+timecounter;
}
function starttimer(counter,ans)
{
var cook
timecounter=parseInt(readCookie(<%=chr(34) & examname&"totaltime"& chr(34)%> ))
var index=-1
if(ans=="A")
index=0
else if(ans=="B")
index=1
else if(ans=="C")
index=2
else if(ans=="D")
index=3
if(document.examform.qno.value-1<=counter&&index!=-1)
document.examform.elements[index].checked=true
timer=setInterval("change()",1000)
}
function stoptimer()
{
writeCookie("<%=examname&"totaltime"%>");
clearInterval(timer)
}
function change()
{
var hrs,mins,secs;
hrs=parseInt(timecounter/3600);
mins=parseInt(timecounter/60);
secs=timecounter%60;
window.status="Time Remaining : "+hrs+":"+mins+":"+secs;
rem_time.innerText="Time Remaining :"+hrs+":"+mins+":"+secs;
timecounter--
if(timecounter==-1)
{
store_ans()
stoptimer()
document.examform.submit()
}
}
function store_ans()
{
var elems=document.examform.elements
var ans=""
for(var i=0;i<elems.length;i++)
if((elems[i].type=="radio"||elems[i].type=="checkbox")&&elems[i].checked)
ans=ans+elems[i].value
document.examform.answer.value=ans
if(ans=="")
document.examform.answer.value="Not Attempted"
stoptimer()
}
</script>
document.cookie: get and set the cookies associated with the current document (Mozilla Developer Network)
You can manipulate cookies with vanilla JavaScript using the document.cookie global.
To store multiple cookies, you have to assign document.cookie multiple times, e.g to store var a = '1'; var b = '2' you do
document.cookie = "a=1";
document.cookie = "b=2";
To read the cookie string, simply reference document.cookie, e.g console.log(document.cookie)
Also, your post has several editing and grammatical mistakes. Additionally, this is a question which can be easily answered with a Google search.

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
}

Microsoft Dynamics CRM 2011/2013

In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}

Keeping clicked checkboxes state after page refresh

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

remove value from the list

I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.

Categories

Resources