Refresh background pages using Javascript? - javascript

Scenario :
Working on an e-commerce website.
I have put together a function which :
updates the total number of
items in the basket icon, and
also adjusts it when the user increases
or decreases the qty amount for an item in the actual basket page.
I am using local storage to fetch and update the information.
This particular basket page opens up in a new window. The basket icon is shown in pretty much all other pages of the website.
Problem :
Even if the user has another page open in the background, I want that page to also refresh to reflect the new qty amount displayed in the basket icon, the second they adjusts the qty amount from the basket page.
When the user closes the basket page and wants to continue
shopping, the original page - prior to opening the basket page - has
the updated number of items in the basket icon.
There are three ways a user can adjust the number of items in the basket. Each product has an increase / decrease button, and also an input field where the user can enter a number manually and the basket qty icon will reflect the new change.
Following function will change the qty of the item when user clicks either increase or decrease symbol
document.body.addEventListener("click", function(e) {
var reg = /\w{7}\d+/g;
if (e.target.classList[0] === "increaseQty") {
var getItem = getLocalStorageData("basketData");
getItem.basketQty++;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.previousSibling.value++;
var currentProduct = e.target.previousSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]++;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.previousSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else if (e.target.classList[0] === "decreaseQty") {
if (e.target.nextSibling.value > 0)
var getItem = getLocalStorageData("basketData");
getItem.basketQty--;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.nextSibling.value--;
var currentProduct = e.target.nextSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]--;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.nextSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else {
return;
}
})
$("#basket-content").on("change", 'input[name="nameQty"]', function() {
var getItem = getLocalStorageData("basketData");
var regNum = /\d+/;
var currentQty = this.id;
var currentVal = this.value;
var reg = /\w{7}\d+/g;
var product = currentQty.match(reg);
product = product.toString();
if (!regNum.test(currentVal) || currentVal < 0) {
alert("Please enter a valid number");
document.getElementById(currentQty).value = getItem[product];
return;
} else if (currentVal > getItem[product]) {
var addQty = currentVal - getItem[product];
getItem.basketQty += addQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
} else if (currentVal < getItem[product]) {
var minusQty = getItem[product] - currentVal;
getItem.basketQty -= minusQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
}
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][product]) {
var currentPrice = currentVal * productCats[i][product].price;
document.getElementById(currentQty).parentNode.nextSibling.innerText = "£" + currentPrice.toFixed(2);
getTotalCost();
}
}
updateLocalStorage(getItem);
});

Related

Apply multi-prompt validation in Cognos

I have three text prompts and want to validate them as a group, requiring the user to input value in one or more prompts before proceeding.
For e.g. I have First Name, Last Name and Student ID fields and want to group these together such that the user has to input value in at-least one prompt before proceeding. Here is what I have so far, but it is not recognizing the value in second and third fields.
var report = cognos.Report.getReport('_THIS_');
var fName = oCR.prompt.getControlByName('FirstName');
var lName = oCR.prompt.getControlByName('LastName');
var studentId = oCR.prompt.getControlByName('StudentID');
var prompts = [fName ,lName ,studentId];
var i = 0;
var promptsLength = prompts.length;
for ( i = 0; i < promptsLength ; i++) {
prompts[i].setValidator(validate);
}
function validate() {
var result = false;
for ( i = 0; i < promptsLength; i++) {
if (prompts[i].getValues().length > 0) {
result = true;
}
if (prompts[i] != this) {
prompts[i].checkData();
}
}
return result;
}

Store and code values of range sliders as embedded data field in Qualtrics

I would like to store the values of several range sliders, code them as "0"/"1", add them up and store the sum in an embedded data field in Qualtrics. However, with my code below, it only codes and stores the value of the last moved slider.
How can I circumvent that and store the values of all sliders?
Qualtrics.SurveyEngine.addOnload(function()
{
var sliders = document.getElementsByClassName('more-left');
var len = sliders.length;
for ( var i = 0; i < len; i++ ) {
var slider = sliders[i];
slider.addEventListener('change', function() {
updateValue(this);
});
updateValue(slider);
}
function updateValue(slider) {
var id = slider.id;
if (!id) {
return;
}
var val = document.getElementById(id + '_value');
if (val) {
val.innerHTML = slider.value;
}
var question_text = slider.value
if (question_text == 50) {
score = 1;
}
else {
score = 0;
}
Qualtrics.SurveyEngine.setEmbeddedData("Output",score);}});
Thank you!

Can't set the number of paginations with JavaScript

I'm trying to add the numbers of pagination using Javascript. The arrows navigation is working fine but when I try to add the numbers of pages my code doesn't work. I have 2 pages with 10 results each. When I click in the number 1 the console print the number 3. The problem is inside the function createPagination when I create the loop for the page numbers. Any help?
var arrFull = [];
var pageSize = 10;
var pages = -1;
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
number.addEventListener('click', function(event) {
event.preventDefault();
changePagination(pagination);
console.log(pagination);
});
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
When you pass on your pagination variable it passes the last value set to it in that context (the 3 because of its last iteration in the loop).
You should declare a variable inside the click event and assign to it the value of pagination and then pass your local variable to your method:
number.addEventListener('click', function(event)
{
let currentPage = pagination;
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
That should do the trick.
Edit
This is the actual solution:
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
The reason why the number 3 is being returned is because the let currentPage = pagination; line is being executed when the event triggers; by that time the value of the variable pagination is equal to 3, so you need to save its value through every iteration (it can be saving it inside a property within your element outside of the event scope like so: number._pageNumber = pagination;; or as the given example: number.setAttribute("page", pagination);).
Full implementation
<html>
<body>
<!--Element to simulate the pagination-->
<div id="pagination"></div>
<script>
var arrFull = [];
var pageSize = 10;
var pages = 2; // Change to simulate your case (changed the '-1' to '2')
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
// <Here_is_the_sugested_code> //
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
// </Here_is_the_sugested_code> //
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
createPagination(); // Call to the function to simulate the generation
</script>
</body>
</html>

Using a user selected choice from a drop-down to populate a text field in Google Forms

I am creating a Judging Form for a research competition and I am trying to use Google Forms to do so. What I am attempting to do is have a drop down list the Research Poster Numbers and have then have the user selected choice from the drop down fill text field for the poster title. I will be pulling the both the Poster Number and Title from an existing spreadsheet.
var caseScoreForm = FormApp.openById('FormTitle');
var scoreSheet = SpreadsheetApp.openById('SpreadSheetName');
var lastRow = scoreSheet.getLastRow();
function fillposterNumbersDropDown(posterNumberRange) {
var posterNumber = caseScoreForm.addListItem();
var posterNumberValue = "";
var posterNumberLog = "";
var posterNumberArr = [];
var posterNumberRange = scoreSheet.getRange('Score Sheet!A2:' + lastRow).getValues();
// loads the posterNumber array
for (var i = 0; i < posterNumberRange.length; i++) {
posterNumberValue = posterNumberRange[i][0];
Logger.log(posterNumberValue);
posterNumberLog = posterNumber.createChoice(posterNumberValue);
posterNumberArr.push(posterNumberLog);
}
posterNumber.setTitle('Poster Number:').setChoices(posterNumberArr).setRequired(true);
}
function setPosterTitleTextResponce(posterTitleRange) {
var posterTitleRange = scoreSheet.getRange('Score Sheet!B2:' + lastRow).getValues();
var posterTitle = caseScoreForm.addTextItem();
var posterTitleValue = "";
var posterTitleLog = "";
var posterTitleArr = [];
var posterNumberIndex = null;
var posterNumberChoices = FormApp.getActiveForm().getItems(FormApp.ItemType.LIST)[1].asListItem().getChoices();
var userChoice = getUserChoice();
//get the users choice index from the posterNumber dropdown
if (userChoice != null) {
for (var i = 0; i < posterNumberChoices.length; i++) {
if (userChoice == posterNumberChoices[i]) { // need getUserChoice();
posterNumberIndex = i;
break;
}
}
}
//loads the posterTitle array
for (var i = 0; i < posterTitleRange.length; i++) {
posterTitleValue = posterTitleRange[i][0];
posterTitleLog = Logger.log(posterTitleValue);
posterTitleArr.push(posterTitleLog);
}
//print out the posterTitle using the posteNumbers index
posterTitle.setTitle('Poster Title:').setRequired(true); // need way to wright to textfield
}
I think all I have left to do is just get the users choice for the active form and print it to the poster Title text field. I know there is the Get pre-filled URL link in Google forms, but we are projecting about 200 entrees for this competition.
If any one has any help/tip/suggestions or have any alternatives, please let me know.

change numbers from dynamic elements

I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element...
var button = $('#add');
button.click(function()
{
var filmnamn = $('#name');
var filmnamnet = filmnamn.val();
var betyg = $('#star');
var betyget = betyg.val();
betyget = Number(betyget);
if(filmnamnet == 0)
{
$('#name').css('background-color', 'red');
}
if(betyget == 0)
{
$('#star').css('background-color', 'red');
}
if(betyget == 0 || filmnamnet == 0)
{
alert("Vänligen fyll i fälten korrekt");
}
else
{
var array = new Array();
array.unshift(betyget);
array.unshift(filmnamnet);
film_array.unshift(array);
betyg_array.unshift(array);
updateFilmList();
}
});
var film_list = $("#filmlista");
var film_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var filmen = film_array[0][0];
var grade = film_array[0][1];
var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>';
film_list.append(element);
changeNumber();
}
And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem?
function changeNumber(){
var elements= document.getElementsByClassName("betyg");
for (var i=0; i<elements.length; i++) {
var element = elements[i];
var length = parseInt(element.innerHTML);
var x=Array(length+1).join("*");
element.innerHTML=x;
}
}

Categories