How to persist checkbox selection with page refresh? - javascript

I'm working on a shopping list web app in Eclipse using Java, Thymeleaf, Spring, HTML and some CSS. I used HTML to code a checkbox list into the app so when I am done with a certain list I can click the checkbox and it puts a line through the text. However, when I refresh the page the checkbox doesn't stay checked. I'd like to be able to keep the box checked with a page refresh. I've tried various different bits of code from other Stack Overflow questions like coding Javascript into the HTML page, but nothing seems to work so far. Here's my HTML code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layouts/basic">
<link rel="stylesheet" th:href="#{/templates.css/main.css}" />
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 15px;
}
.strikethrough:checked+.strikeThis {
text-decoration: line-through
}
</style>
</head>
<body layout:fragment="content">
<div class="row">
<h1>Shopping Lists</h1>
<!-- a simple button for later to add shopping lists -->
<a href="/" th:href="#{|/ListsofLists/add|}"><input type="button"
value="Add list" /></a>
<table>
<thead>
<tr>
<th>Name</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody class="list">
<tr th:each="list : ${lists}">
<td><input type="checkbox" name="check" class="strikethrough"
value="1" /> <label for="check" class="strikeThis"
th:text="${list.name}"> Name </label></td>
<!-- <td th:text="${list.name}"></td> -->
<td>Show</td>
<td><form method="POST">
<input type="hidden" name="listId" th:value="${list.id}" />
<button type="submit">Delete</button>
</form></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I will try to answer as many questions as possible in order to figure out this question. Apologies if it's something rather simple, I am new to coding and still learning.

You need to save your checkbox state to local storage. So the browser can check the boolean value true or false of your checkbox when it loaded / refresh.
Here's the tutorial for storing checkbox state on local storage :
https://www.sitepoint.com/quick-tip-persist-checkbox-checked-state-after-page-reload/

You could use local storage to store user's checkbox selection and on page refresh you can retrieve the checkbox selection from local storage and set the checkbox selection.
Simple examples of using local storage is:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
You can view more details about local storage on w3schools here(http://www.w3schools.com/html/html5_webstorage.asp)
Relevant to your case you can use jQuery and local storage using this guide(https://www.sitepoint.com/quick-tip-persist-checkbox-checked-state-after-page-reload/) to remember user's selection when a checkbox is clicked and retrieve them when page refreshes.

You need to identify a way to store that the checkbox has been selected. Typically solutions involve localstorage/cookies, sessions, or through a database.
When the box is checked, store it somewhere. Similarly, if it's unchecked you need to store that preference as well. And then with each page load, you need to do a check to see if there is a saved preference or you should just go to the default.
There are benefits to each storage option. Local storage & cookies are very easy to implement. But they're located on the client's machine, thus they're volatile. If it's important information, don't rely solely on this method. Session Storage (php or HTML5) will last for the duration of the browser session. This is helpful if you don't need the data to persist as a permanent selection. If you need it to be permanent, you need to save things out to a database.

There are many ways to do this.
One of the more popular methods is to use JavaScript cookies. In this method you would set a cookie like checkbox=true and grab that value on page refresh.
Another method is to set a location hash parameter in JavaScript, likewise reading this parameter on page load.
Lastly, you could also use HTML5 LocalStorage.
These are all the client-side methods for doing this. You can always do this on server-side using a HTML parsing script written in PHP or your language of choice.
As I mentioned on another SO question recently, running a page refresh clears out all of the values set before in both JavaScript and HTML forms. Everything goes. For future people who read this, please do not use page refresh in JavaScript code. It makes many people very angry, and causes them to pull out their hair uncontrollably.

Related

Get/display Page ID - Confluence Internal Code

I am trying to display a page's ID within itself i.e. within the content of the page the page ID is displayed.
Q/A within the community recommend using **$content.getIdAsString()** but that has not worked. I've tried to input this within an HTML macro and without one as well but to no avail.
I'm trying to get the ID of the page so that an HTML code block could reference the page it is included on instead of inputting the page ID by hand every single time.
Here is the code that I am currently using:
<input type="image" src="/download/attachments/171705685/BackPurple.jpg"
onclick="location.href=document.referrer; return false;">
<input type="image" src="/download/attachments/171705685/DownloadPurple.jpg"
onclick="location.href='/spaces/flyingpdf/pdfpageexport.acti‌on?pageId=17170615‌​3';"> <-- This pageID
I want this highlighted pageID is what I am hoping can be pulled in automatically
Looking forward to your responses.
I use this to get the Page ID of a page do my users to have to go looking for it.
<tr>
<td>UNDERLYING PAGE ID:</td>
<td> $content.getId() </td>
</tr>

Presenting Cookies on a PHP based site

My PHP/HTML/Javascript skills are 0 but I have managed to create a site using a default template which I have modified.
What I am trying to accomplish is to have the browser print out the Cookie Name and Value if it exists. This is for a lab exercise that I'm currently working on. The lab itself is not how you program but rather how you configure Cookie Persistence and as part of the lab I want the student to easily display the cookie on the webpage.
Previous examples have been with HTML/JavaScript and the following code:
<script language="javascript">
function showCookieLink() {
var ele = document.getElementById("CookieLink");
ele.style.display = "block";
}
</script>
<BODY bgColor="#0066FF" onload="javascript:if (document.cookie) showCookieLink()">
<tr>
<td colspan="2" align="center" vAlign="top">
<font face=Arial>
<div id="CookieLink" style="display: none;"><b><font color=#0000f0>Display Cookie</b></div>
</font>
</td>
</tr>
This previous example have been brilliant. It will print out the clickable link "Display Cookie" (if a cookie exists) and when clicked it will pop up a new smaller window with the Cookie Name and Value.
For some reason this does not work anymore. I have tried several different browsers but they all act the same. JavaScript is enabled on the user.
I have been trying different types of preformatted-codes to fix this but none work (or I just suck at programming/scripting).
Can you guys please help me with this? Perhaps you can print out an example code that I can copy/paste into my current php code?
Thanks in advance!
According to this post, document.cookies will only work in a web server, not in just html that is served up from the file system. Does your url look like http://localhost or file:///your/file/here.html? It should look like the http:// one.
You also have some issues with your code. you dont close the second font tag, <script> should either be in a <head> or <body> tag, your <body> tag shouldn't be capitalized. Look here for a basic template.

override picklist value in visualforce page

I am using a picklist in visualforce page, through apex:inputField in a form. I am saving that value in custom object. And that value is being saved in object. But when I will open that record in the same form (visualforce page). When the form is being loaded that saved value was there. but when the form has been loaded, the value become null and --None-- was selected.
I tried to use javascript with alert, but it was showing that right value. I couldn't find out the issue.
I have used below code:
<apex:pageBlockSectionItem id="Menopausal_StatusItem">
<apex:outputText value="Menopausal Status:" />
<apex:outputPanel >
<apex:inputField value="{!msd.AgeVal__c}" id="ageValId" label="" style="display:none;"/>
<apex:inputField value="{!msd.Menopausal_Status__c}" id="Menopausal_Status" required="true"/>
</apex:outputPanel>
</apex:pageBlockSectionItem>
<!--<script>
alert('{!msd.Menopausal_Status__c}');
alert(document.getElementById('pageId:formId:pageBlockId:pageBlockSectionId:Menopausal_StatusItem:Menopausal_Status').value);
</script>
-->
This is a dependent picklist (msd.Menopausal_Status_c) and the controlling pick list is msd.AgeVal_c.
Please help me. Thanks in advance.
I think this has to do with the dependent pick lists. Do you have a value in AgeVal__c? If not, Menopausal_Status__c might not be correctly rendered when loading it in the Visualforce page.
You could verify this by temporarily making the controlling pick list visibility, to check its content.

to retain values in form using struts tags and dynamic behaviour through Javascript

I have a JSP page containing a ADD button to add the rows(a HTML code) via Javascript.
I now need to retain the value in my form by replacing the codes in JSP by struts-tags.
How should I then communicate from struts-tags and JS. Since all the HTML code lies in JS, how should it use struts-tags???
Please help!!
Your question is too vague to give an appropriate answer. However, I recently did something similar to this so I will try and give you a few guidelines.
1.) If you are hoping to populate these rows with information from the server this will require an ajax call. Most likely to an action that returns a snippet of jsp containing only a table row.
I suggest avoiding the struts2-jquery plugin for this unless you already are using it in your application. I would just use jQuery - http://api.jquery.com/jQuery.ajax/
2.) If you wish to gather user input in these rows you will just have to make sure to use appropriate naming for your fields.
Eg: In your java action you have a List< String > names.
You would need to generate the following html via js.
<tbody>
<tr>
<input type="text" name="names[0]">
</tr><tr>
<input type="text" name="names[1]">
</tr><tr>
<input type="text" name="names[2]">
</tr>
</tbody>
3.) If you wish to keep track of the number of added rows you could use this in your jsp...
<s:hidden name="rowsCount" id="rowsCount" value="0">
then within your javascript change the value of that input.
Hope one of those 3 helped!

Javascript and CSS that can replace alerbox. Alert Box is so unprofessional [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Custom alert using Javascript
I want to create a confirmation message-"Do you want to proceed deleting? [Yes] or [No]".
I have a table with many data rows where the delete link is clicked in a particular row, the data in the row is deleted in the database. When the user clicks the delete option, i want to show the confirmation message first, so that user can validate his actions before deleting.
How can i do that dynamically using java script and css? I don't want to use alerBox() as it is ugly and is so unprofessional.
I am currently working for my school project-jsp and Java Servlet.
Hope any experts will help me. I love this forum as people here are very helpful. Advance thanks!
Actually you could do
window.alert = function(text) { /* some code to show a fancy dialog */};
window.confirm = function(question) { /* some code to show a fancy dialog and return the result */}
Problem is you're messing around where ought not mess around but the advantage is that even in 3rd party code any alerts() or confirms() will come up as your custom dialogs and the code will be simple to read (instead of $.dialog({options}) you just use a normal alert() or confirm call)
Because of the way JavaScript event handling works, there cannot exist any "drop-in" replacement for confirm, but popular JavaScript libraries such as jQuery UI include "modal dialog" features that can be used to achieve a similar effect.
http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/ is an example of how this works. Your "delete" button would not be set up to submit the form but rather open the modal dialog, which would submit the form if the user clicks OK.
If you want really to look good try this approach:Use for example jQuery and jQueryUI.
In your page put this:
<head>
<link rel="stylesheet" type="text/css" media="all" href="pathtoyourappfolder/jquery/css/black-tie/jquery-ui-1.8.4.custom.css" />
<script type="text/javascript" src="pathtoyourappfolder/jquery/js/jquery-1.4.2.min.js'" ></script>
<script type="text/javascript" src="pathtoyourappfolder/jquery/js/jquery-ui-1.8.4.custom.min.js'" ></script>
</head>
<body>
<div id="dialog-confirm" title="DELETE">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
Are you sure you want to delete this record?</p>
</div>
<table id="TblName">
<tr>
<td class="actions">
del
</td>
<td>...</td>
</tr>
<tr>
<td class="actions">
del
</td>
<td></td>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#TblName td.actions a.del').click(function(event){
$("#dialog-confirm").dialog('open');
});
}
</script>
</body>
You can add onclick="deleteRow(row_id, this)" to each delete link. Usage of row_id assumes the table is being generated dynamically from a given set and you have an identifier to provide and pick the data to delete. The this is useful to remove the <tr> using Javascript.
Oh and of course the function would make a dialog popup. Use jQuery for that.
You can try FaceBox and FacyBox
http://chriswanstrath.com/facebox/
http://www.bitbonsai.com/facybox/
You can rewrite the functionality. I am intending you wanna know what's happening and how to achieve effects, instead of using a library like jQuery. jQuery and derived solutions can make your life easier, but if you want to know HOW to make it, continue reading.
First, you should make your own "alertBox", with your preferred CSS styling (including it's position) [I suggest position absolute, z-index:2], then in the CSS let its display property as hidden.
OK, now when user clicks your delete link/button you trigger a native javascript confirm dialog. Replace this confirm call, to a function that will display your own styled menu. changing its CSS display property from hidden to "block".
On your own styled menu buttons Yes/No, attach events, one for each button, with respective action (hide menu, or deleting row, removing current line from table...).
Well, that's the idea. Hope you enjoy.

Categories

Resources