Persist checkbox state while jsp reload - javascript

I have code where I want to keep more than one checkboxes state(checked) when the jsp page reloads after coming back from controller.I can successfuly retrieve the selected values in sesssion but am unable to get the check boxes checked.
My code snippet is as follows:
<%!public String portarray[] = null;%>
<%if (request.getSession().getAttribute("portselected") != null) {
portarray = (String[]) request.getSession().getAttribute("portselected");
for (int i = 0; i < portarray.length; i++) {%>
alert(
<%=portarray[i]%>
);
$("#\"removebasket"+<%=portarray[i]%>+"\"").attr("checked", true);
$('#removebasket13989')[0].checked = true;

firstly use document.ready to only do this when the page is fully loaded.
also, use .prop() for setting the check state
// only when page fully loads
$(document).ready(function() {
// use prop
$('.myCheckbox').prop('checked', true);
});
you should also make sure that $("#\"removebasket"+<%=portarray[i]%>+"\"") is correct byt viewing the source of your page when it reloads

Related

Link that preselect dropdown option with jQuery

I have a select with options that have values that are populated with jQuery based on data attributes from divs. When a user select an option, the div with the data attribute that matches the value of the option is displayed. Now I'm trying to create a deep linking option, so when I have a url like https://my-site.com/page/#option-2 the option-2 is preselected in the select and the div with data attribute option-2 is displayed. So far I have this javascript:
$(window).on('load', function() {
let urlHash = window.location.hash.replace('#','');
console.log(urlHash);
if ( urlHash ) {
$('.dropdown').val(urlHash);
$('body').find('.location').removeClass('is-active');
$('body').find(`.location[data-location-hash=${urlHash}]`).addClass('is-active');
}
});
If I enter the url https://my-site.com/page/#option-2 the site goes in infinite loop and never loads without displaying any error in the console.. If I refresh the page while loading, the console.log is displayed with the correct string that I'm expecting, but the .location[data-location-hash=option-2] is not displayed and the option is not selected... I'm using the same code for the change function of the dropdown and is working, but it's not working in the load function.. Is there anything I'm missing?
JSFiddle, if it's of any help:
https://jsfiddle.net/tsvetkokrastev/b0epz1mL/4/
Your site is looping because you are doing a window.location.replace To get the urlHash you should use
$(window).on('load', function() {
var href = location.href; // get the url
var split = href.split("#"); // split the string
let urlHash = split[1]; // get the value after the hash
if ( urlHash ) {
$('.dropdown').val(urlHash);
$('body').find('.location').removeClass('is-active');
$('body').find('.location[data-location-hash='+urlHash+']').addClass('is-active');
}
});
https://codepen.io/darkinfore/pen/MWXWEvM?editors=1111#europe
Solved it by using a function instead of $(window).on('load').. Also added $( window ).on( 'hashchange', function( ) {}); to assure that the js will run again after the hash is changed.
Here is an updated jsfiddle: https://jsfiddle.net/tsvetkokrastev/b0epz1mL/5/

How to display same content after closing or reloading

Hi I wrote a code which has local storage applied to the options on the page. The only problem I am having is that I am unable to save the page which the options had searched. As you can see in the js fiddle. The options stay the same as which they were selected even after refresh. But when you click on the search function. It takes you to that image with those options applied. But when you refresh the page it goes back to the original. How would I keep the same display after refresh
This is my code for the local storage, it works for the options but not for the display of what the search has produced.
$('#browsepagebutton').on('click', function() {
$('select').each(function() {
var id = $(this).attr('name');
var value = $(this).find("option:selected").val();
console.log("SetItem : " + id + " with value : " + value)
localStorage.setItem(id, value);
});
});
$(document).ready(function() {
$('select').each(function() {
var id = $(this).attr('name');
if (localStorage.getItem(id) !== null) {
var value = localStorage.getItem(id);
$(this).val(value)
}
});
})
Js fiddle of code https://jsfiddle.net/387tnzoy/4/ (Note the function wont work)
The js fiddle does show the code just so that you can get an idea of what is happening for example. When I apply filters such as animation on life of pi and click the submit button it will only show the life of pi image undreneath the options because it is the only one set with that option. The only problem now is that I want local storage to save that page. So that when I refresh it is still on that display.
$('select option').each(function() {
var id = $(this).attr('name');
if (localStorage.getItem(id) != null && id=='name') {
$(this).attr("selected", "selected");
}
});
You'll just need to run the filtering after populating the options. Note that they will still flash on the screen before the JavaScript is run so you might want to keep them hidden until that.
$(document).ready(function() {
$('select').each(function() {
var id = $(this).attr('name');
var value = localStorage.getItem(id);
$(this).val(value)
});
$('#browsepagebutton').click(); // Add this
})
Updated fiddle: https://jsfiddle.net/387tnzoy/6/
There are multiple issue with your fiddle as described below.
Remove onclick="saveValues()" from Search button.
Check on document ready if localstorage has value than play with your localStorage checking code
Your Year dropdown have similar values for multiple options like <option value="5">2013</option>
<option value="5">2014</option>
<option value="5">2015</option> as you can see same value 5 here
And yes #kaivosukeltaja mentioned you have to click Search if localstorage has value on ready event
I have updated fiddle you can find here

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

Django Admin - RelatedObjectLookups - How Does it refresh and set the select on the parent window?

I want one of my forms to work just like the admin page does so I figured I'd look in the code and see how it works.
Specifically I want the user to be able to click a "+" icon next to a select list and be taken to the admin page's popup form to add a new item.
When they enter a new item there, I want that new item to appear in the select box, and be selected (Just like how this feature works on the admin pages).
I copied the admin js libraries into my own template, and I made my link call the same JS function and the popup windows does open correctly, but after I save a new object the popup window goes blank instead of closing, and nothing happens on the parent page.
Here's what I put in my page:
...
<td>
<div class="fieldWrapper">
<select name="form-0-plasmid" id="id_form-0-plasmid">
...
</select>
<img src="/media/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>
</div>
</td>
...
I tried stepping through the javascript on the admin form to see how it's working, but I'm not seeing anything that would close the window or populate the parent window's select.
Thanks in advance for any help.
Update 3
I'm getting this javascript error when dismissAddAnotherPopup is run
"SelectBox is not defined"
Which is pointing to this line in dismissAddAnotherPopup
SelectBox.add_to_cache(toId, o);
I thought I knew Javascript, but I don't see where that variable is supposed to come from :-(
Update 2
Everything seems to be firing properly. After I click save on the popup window I get a blank page. This is the source of that page:
<script type="text/javascript">opener.dismissAddAnotherPopup(window, "9", "CMV_flex_myr_GENE1_._._WPRE_BGH");</script>
So it would seem that this javascript isn't being executed or is failing.
Update
Here is the relevant code that Daniel mentioned. So the only problem is that this code either isn't firing, or is firing incorrectly.
django/contrib/admin/options.py:
...
if request.POST.has_key("_popup"):
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
# escape() calls force_unicode.
(escape(pk_value), escapejs(obj)))
...
/media/admin/js/admin/RelatedObjectLookups.js:
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elem.nodeName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
Ok, the javascript simply uses the id attribute of the launching element to identify the select field to update. (after removing 'add_' from the beginig).
So I simply changed the link's id attribute to match the select element's id in my template:
<img src="/media/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>
Wow I wish this had been documented somewhere! I lost a few hours on this.
(See my updates to the question for more technical details on how it all works.)
The trick - and it's a bit of a hack, actually - is what happens when you click save on the popup in the admin.
If you look at the code of response_add in django.contrib.options.ModelAdmin, you'll see that when you save an item in the popup, the admin returns an HttpResponse consisting solely of a piece of Javascript. This JS calls the dismissAddAnotherPopup function in the parent window, which closes the popup and sets the form value appropriately.
It's fairly simple to copy this functionality into your own app.
Edited after updates If admin javascript doesn't work, it's usually because it has a dependency on the jsi18n code - which you include via a URL (not a static path):
<script type="text/javascript" src="/admin/jsi18n/"></script>
I was having the same problem refreshing the select in the parent window, and I solved following this doc
Everything is working fine now
Edit 1:
I was trying to use Select2 to make the select pretty, the single select works fine, the multiple select is giving me headaches for some reason is not updating the info in the parent form.
Anyone tried this before?

Load Html Content if not exist JQuery AJAX

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

Categories

Resources