I need some help understanding how to do what I suppose it should be an easy thing.
In my controller I am converting a PDF into several images, and I can easily get page number being dealt with and total number of pages that needs to be doing. I am putting both in the session with:
request.getSession().setAttribute("currentPageNumber", currentPageNumber);
request.getSession().setAttribute("totalPagesNumber", totalPagesNumber);
On the view I'd like to show a progress bar knowing these values, doing something like CeilingOf((currentPageNumber/totalPagesNumber)*100) but I don't know how to continuously get those updated values.
If I use:
'<%= request.getSession().getAttribute("currentPageNumber")%>'
this will be resolved loading the page (before the session is even being updated with the attributes) and both show up null.
What do I need to do to access these values on the view? Thank you very much for your help
You can't get that directly. Because JavaScript is executed on the client side (browser), and the session data on the server.
Some ways to use session attribute variables in JavaScript:
a hidden input field storing the variable as its value and reading it through the DOM API
an HTML5 data attribute which you can read through the DOM
storing it as a cookie and accessing it through JavaScript
injecting it directly in the JS code, if you have it inline
In JSP:
<input type="hidden" name="totalPagesNumber" value="${sessionScope.totalPagesNumber} />
Javascript:
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, totalPagesNumber;
for (i = 0; i < len; i++) {
if (inputs[i].name == "totalPagesNumber") {
totalPagesNumber = inputs[i].value;
break;
}
}
Here i am looping all the input hidden fields so that you can get all the values in one loop.
${currentPageNumber}
will access the attribute
Related
I have a set of embedded variables, q1_ans, q2_ans, q3_ans, ....
In one of my questions, I would like to read in all these vars one at a time as part of a loop:
Qualtrics.SurveyEngine.addOnload(function()
{
var i;
for (i = 1; i <= 2; i++) {
let ans_q = "e://Field/q" + i + "_ans"
let ans = "${" + ans_q+ "}";
console.log(ans);
}
});
However, this is not reading in the embedded data values. How can I read in my embedded variables in a JS loop?
Embedded data fields are resolved on the server before the page is sent to the browser, so you can't dynamically build and resolve the pipe strings for embedded data fields in JavaScript.
You could pipe all the strings into an array definition, then loop through the array.
Another alternative would be to use Qualtrics.SurveyEngine.getEmbeddedData() if it still works (no longer included in documentation).
I have a JSON response from a server, which returns me a array with 32 objects (in this case). Something like this:
[{object1},{ object2},{ object3}, etc].
Each object have some info that I use to populate an html template. For that, I just use a simple loop:
for(var i = 0; i < api_empresaListar.length; i++)
{
var item = api_empresaListar[i];
var htmls;
htmls = $('...lots of html code');
...
Then it’s just a simple matter of finding/changing the values, and append items on the DOM. Everything works fine. BUT, for some next parts of the code, I would like to access all the info from the object I used to build the html elements (I just show part of the info). So, after searching a lot, I tried to use data, like this:
var tp = htmls.find(".rl_grupo"); // the main div of each html element created in the loop
$(tp).data('key', api_empresaListar[i]); // here, I expected to just insert the object data in each created item.
But when I try it in the console, I got the object info as expected, but always from the last element in the array. Why is that happening? I believe it might be something stupid, but I can’t figure it out.
So, any ideas on how to solve this, or another method to make this work is appreciated. I made it work by setting some "display:none" placeholder html tags and populate those with the info I need later, but looks like a poor solution...
You should not set your htmls variable in the loop. I think that you crush its content every turn, that's why you only have the last item. You should do something like this:
var htmls = $('<div></div>');
for(var i = 0; i < api_empresaListar.length; i++) {
htmls.append($('...lots of html code'));
}
How about setting an index number on each element inside of your html creating code, then iterating over the $('.rl_grupo') elements, like this?
$('.rl_grupo').each(function(){
var index = $(this).data('index');
var currentData = api_empresaListar[index];
$(this).data('key', currentData);
})
I have two HTML pages. On the first page I add values to an array.
thisArray.push("new value");
On the second HTML page I want to print this array to a textArea
for(i=0; i<thisArray.length;i++){
var thisName = thisArray[i];
document.getElementById('listOfNames').innerHTML += thisName + '\n';
}
But when I change the page obviously the browser wont know about the other variable. What's the best way to do this ?
I thought of saving the value locally?
Is this the best way?
Use window.localStorage.
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Example:
window.localStorage.myArray = JSON.stringify(arrayData)
And then parse JSON when read the data on another page.
You can use localStorage to persist the value,
localStorage.setItem('itemName', itemValue);
then to fetch the item just use
localStorage.getItem('itemName');
You can use localStorage.setItem(key,value)
Check out this library which allows you to set and read javascript cookies easily.
https://github.com/js-cookie/js-cookie
Example:
Set cookie on first page:
Cookies.set('thisArray', JSON.stringify(thisArray));
Read cookie on second page:
var thisArray = Cookies.getJSON('thisArray');
You have at least, two options to do what you want, one is pass that variable on the url query like:
www.mypage.com?my_javascript_var=12345
Another option is using localstorage
localStorage.setItem('itemName', varToBeSaved);
then, to get the variable back on any page
var mySavedVar = localStorage.getItem('itemName');
I am attempting to:
Use JQuery to 'loop' through all elements on a page that belong to the same CSS class ("boilerplate")
Check the current value of each against it's server side assigned value (property: StaticPrefill)
Apply a special css class ("editedbackcolor") if the two values do not match (ie I'm trying to flag when someone has edited the prefilled text on textboxes)
CSS I am using:
.boilerplate = assign to all text boxes I'm trying to check on the form
.editedbackcolor = different shade I want to assign to textboxes where current value does NOT equal server side StaticPrefill value.
jQuery code I have so far is:
jQuery(document).ready(function () {
// select each element with class boilerplate and run a function against it
jQuery('.boilerplate input').each(function () {
var target1 = jQuery(this).attr("id");
matchcheck(target1);
});
});
and I'm working on the "matchcheck) function which is where I am having a problem. I'm trying to pull back the server side "StaticPrefill" property value that I can use as a comparison. I've successfully queried this by hardcoding a control name, like:
function matchcheck(){
var TSP1 = '<%= TextBox1.StaticPrefill %>';
// If current textbox value does NOT equal it's static prefill value
if (document.getElementById("Textbox1_textbox1").value != TSP1) {
alert("TB1 has differnt value than static prefill");
// change background color to flag it
jQuery("#Textbox1_textbox1").addClass("EditedBackColor");
}
}
That works fine, but I don't want to use a variable to loop through all elements instead of the hardcoded "TextBox1" in the first line of the function. I've tried different syntaxes in an attempt to put a variable between the '<%= ' and '%>' tags but the page won't compile when I try this.
Is this possible w/o using code behind of some sort? Any suggestions?
An easier approach, if I understand your question, is to bind to the change event in jQuery.
$(document).ready(function() {
jQuery('.boilerplate input').change(function() {
if(jQuery(this).val() !== jQuery(this).attr("prefill")) {
jQuery(this)removeClass('boilerplate').addClass("EditedBackColor");
}
});
});
You will also need to add an attribute called "prefill" to your input elements. You can do that server side or client side. It should look something like this:
<input class="boilerplate" id="input1" type="text" prefill="123" value="123"/>
The caveat here is that if they change it back to the original value, it will still show as changed. I'm not sure if that works for you in your scenario. They did change it per se. You would have to save off the original value as an attribute if it did not exist. The other option is to send down a model, maybe a json object, and compare to that model based on index.
I have a database webmethod that I call via Jquery ajax. This returns an array of data objects from the server. For each data object I want to populate a form with maybe a couple dozen fields.
What is the most efficient way to generate and populate these forms.
Right now, I create a string of the html in my javascript code for each record and then add it to the page. Then I add some events to the new elements.
This works OK in firefox, about 700 ms total for an array of 6 elements, and 4500 ms for an array of 30 elements. However, this is an internal app for my company, and the clients can only use IE8 on their machines. In IE8, this takes 2-10 SECONDS! for and array of length 6 and 47 seconds the one time it was actually able to complete for an array of length 30. Not sure what the ##$% IE8 is doing, but anyways... I need something more efficient it seems...
Thanks!
MORE INFO:
Edit: first thing I do is:
$("#approvalContainer").empty();
Web method signature:
[WebMethod]
public List<User> ContractorApprovals()
So I call the method and then do this with the data:
for (var i = 0; i < data.length; i++) {
displayUserResult("#approvalContainer", data[i], false);
}
formEvents("#approvalContainer");
$("#approvalContainer").show("slow");
displayUserResult looks like this:
var div = "<div style=\"width:695px\" class=..........."
fillForm(div,data)
$("#approvalContainer").append(div)
formEvents does things like add click events, create styles buttons and add watermarks.
fillForm does stuff like this:
$(userForm).find(".form-web-userName").text(userObject._web._userName);
where userForm is the div created in the displayUserResult function, and userObject is one of the objects in the array returned by the ajax call.
Please let me know if you need more information.
You are doing too much DOM manipulation. Every .append and .find and .text inside your loop makes it slower.
The most efficient way is to build an entire HTML string and append that once. I'm not going to bother with the displayUserResult function, and just modify your function that handles the data:
var div = "<div style=\"width:695px\" class=...........",
html = "";
for (var i = 0; i < data.length; i++) {
// Keep adding on to the same html string
html += div + data[i]._web._userName + "</div>";
}
// After the loop, replace the entire HTML contents of the container in one go:
$("#approvalContainer").html(html);
However, while this is fast, note that this is only appropriate if _userName doesn't contain special characters, or is already HTML escaped.