I'm trying to get the values stored in the local storage variables in order to display them !!
but the problem here is that the display of the values is immediate, in other words :
the first time of loading the page nothing is displayed then every time i refresh the page the next value is displayed.
function ChoixDeQuestion (){
var ide=window.sessionStorage.getItem('idenq');
GetQuest(10);//--> this function store some values in the 'questions' var
var storedQuest=JSON.parse(window.localStorage['questions']);
var i;
for ( i = 0; i < storedQuest.length; i++)
{
var newdiv = document.createElement('div');
switch(storedQuest[i].type) {
case 'text':
newdiv.innerHTML += "<br> Question " + (i + 1) + " : "+storedQuest[i].text+" ? <br><br><textarea name='quest"+(i + 1)+"' rows=4 cols=40 >type here...</textarea>" ;
break;
case 'simple':
var questId=storedQuest[i].id;
GetChoix(questId);
var storedChoix=JSON.parse(window.localStorage['choices'+questId]);
newdiv.innerHTML += "<br> Question " + (i + 1) + " : "+storedQuest[i].text+" ? <br><br>";
for (var j = 0; j < storedChoix.length; j++) {
newdiv.innerHTML += " " + (j + 1) +"- "+storedChoix[j].text+ " <input type='radio' name='choix"+(j + 1)+"'>";
}
break;
case 'multiple':
var questId=storedQuest[i].id;
GetChoix(questId);
var storedChoix=JSON.parse(window.localStorage['choices'+questId]);
newdiv.innerHTML += "<br> Question " + (i + 1) + " : "+storedQuest[i].text+" ? <br><br>";
for (var j = 0; j < storedChoix.length; j++) {
newdiv.innerHTML += " " + (j + 1) +"- "+storedChoix[j].text+ " <input type='checkbox' name='choix"+(j + 1)+"'>";
}
break;
document.getElementById('results').appendChild(newdiv);
}
}
thie method is called in the
$(document).ready(function() { ChoixDeQuestion();});
So how can I get all the values shown in the same time when the page is loaded ??
Related
I am iterating through a JSON-File and get a different amount of features for given locations. This can be 10 or there are only 2, depending on the location. I am able to retrieve the data from the JSON for each location and iterate through all of them at this spot.
GOAL: Depending on the number of features at the location I would like to create a table with max. 3 columns and number/3 rows. If there are e.g. 10 Features just make 3-3-3-1 (2 empty boxes).
var overlay = new ol.Overlay({
element: document.getElementById('overlay'),
positioning: 'bottom-left'
});
var displayImage = function(pixel) {
var features = [];
map.forEachFeatureAtPixel(pixel, function(feature,layer){
features.push(feature);
},{hitTolerance: 10});
if (features.length >0) {
var rows = Math.ceil(features.length / 3);
var imag = [];
var years = [];
console.log(features);
for (var i = 0, ii = features.length; i < ii; ++i) {
imag.push(features[i].values_.pointAttributes.Image);
years.push(features[i].values_.pointAttributes.Year);
overlay.setPosition(features[i].values_.geometry.flatCoordinates);
var element = overlay.getElement();
console.log(imag);
element.innerHTML =
"<img ID=\"theImage\" src= \"\">\n\
<table class=\"fototable\"> \n\
<tr><td> <button class=\"btn\" data-img=" + imag[0] + " onclick=\"myFunction(this)\"> " + years[0] + " </button></td>\n\
<td> <button class=\"btn\" data-img=" + imag[1] + " onclick=\"myFunction(this)\"> " + years[1] + " </button> </td>\n\
<td> <button class=\"btn\" data-img=" + imag[2] + " onclick=\"myFunction(this)\"> " + years[2] + " </button> </td></tr> \n\
<tr><td> <button class=\"btn\" data-img=" + imag[3] + " onclick=\"myFunction(this)\"> " + years[3] + " </button></td> \n\
<td><button class=\"btn\" data-img=" + imag[4] + " onclick=\"myFunction(this)\"> " + years[4] + " </button></td>\n\
<td><button class=\"btn\" data-img=" + imag[5] + " onclick=\"myFunction(this)\"> " + years[5] + " </button> </td></tr></table>";
As you might see I hard-coded it so far but this is not the best solution. I tried to do something like adding the ...etc. to a string but I did not manage to get the 3-columns max then.
Any help/link will be appreciated!
Have fun :)
let test = [1,2,3,4,5,6,7,8,9,10,11];
let innerHTMLStart = "<table>";
let innerHTMLEnd = "</table>"
let innerHTML = innerHTMLStart;
let lastIndex = test.length - 1;
//loop over our items
for(var i = 0; i < test.length; i++) {
//first iteration
if(i % 3 == 0 && i == 0) {
innerHTML = innerHTML + "<tr>"
//modulo 3 but not first iteration
} else if(i % 3 == 0 && i > 0) {
innerHTML = innerHTML + "</tr><tr>"
}
//add cells to the table
innerHTML = innerHTML + "<td>" + test[i] + "</td>";
if(i == lastIndex) {
//last iteration? how many <td>?
//always finish with 3 cells
if((i+1) % 3 == 0) {
innerHTML = innerHTML + "</tr>"
} else if((i+1) % 2 == 0) {
innerHTML = innerHTML + "<td></td><td></td></tr>"
} else {
console.log("else")
innerHTML = innerHTML + "<td></td></tr>"
}
}
}
innerHTML = innerHTML + innerHTMLEnd;
console.log(innerHTML)
I didn't test that code and probably contains errors but as i understand your question the code below should be suits your needs.
var content ="<table class=\"fototable\"><tr>";
for(var t=0; t<imag.length; t++){
content+="<td><button class=\"btn\" data-img=\" + imag[t] + \" onclick=\"myFunction(this)\"> " + years[t] + " </button></td>\n\";
if((t+1)%3==0 && t!=(imag.length-1)){
content+="</tr><tr>";
}
}
for(var i = 0; i<3-imag.length%3; i++){
content+="<td></td>";
}
content+="</tr></table>";
element.innerHtml = content;
So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.
setScreen('LogIn');
var balance;
var curbal = [];
var totalAccts=[];
onEvent("saveAcct", "click", function() {
var username = getText('createUserInput');
var password = getText('createPassInput');
appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
console.log("Username: " + username + " Password: " + password);
console.log(totalAccts);
setScreen('LogIn');
});
onEvent('makeAcct', 'click', function(){
setScreen('CreateAcct');
setText('createUserInput', "");
setText('createPassInput', "");
setText("userInput", "");
setText("passInput", "");
hideElement('alert');
});
onEvent('addMoney', 'click', function(){
setNumber('balance', balance + getNumber('addInput'));
balance = balance + getNumber('addInput');
setNumber('addInput', '');
console.log(balance);
});
onEvent('subMoney', 'click', function(){
setNumber('balance', balance - getNumber('subInput'));
balance = balance - getNumber('subInput');
setNumber('subInput', '');
console.log(balance);
});
onEvent('login', 'click', function(){
balance = 0;
changeEnBal(totalAccts, curbal);
});
onEvent('logout', 'click', function(){
changeExBal(totalAccts, getNumber('balance'), curbal);
hideElement('alert');
setText('balance', 0);
setText("userInput", "");
setText("passInput", "");
setScreen('LogIn');
});
onEvent("goBack", "click", function() {
setScreen('LogIn');
});
function changeEnBal(list, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
setScreen('Account');
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balance = balList[a];
setNumber('balance', balList[a]);
setScreen('Account');
console.log(balList[a]);
}
}
}
}
for (var b = 0; b < balList.length; b++) {
if (balList[b] != (user + " " + pass + " " + balList[b])){
showElement('alert');
}
}
}
function changeExBal(list, curBal, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
list[i] = user + " " + pass + " " + curBal;
appendItem(curbal, curBal);
console.log(curbal);
console.log(list[i]);
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balList[a] = curbal;
list[i] = user + " " + pass + " " + curBal;
}
}
}
}
console.log(totalAccts);
}
As suggested in some of the comments I would change your for loops to start with a zero index:
for (var i = 0; i < list.length; i++)
and
for (var a = 0; a < balList.length; a++)
In my table 1st column has a tags with href's and 3rd column has some text. So, I want to save all href's into an array where their respective 3rd column matches some string and use it for later purpose. I had tried the following code nothing seems wrong to me, can some one assist me with this.
function findimagelinks(){
var rows = jQuery(".sortable tr.even").length + jQuery(".sortable tr.odd").length;
var imglinks = [];
for (i=0; i<rows; i++){
var conditionvalue =jQuery(".sortable tr:eq(i+1) td:eq(3)").text();
if(conditionvalue == "some string"){
imglinks[i] = jQuery(".sortable tr:eq(i+1) td:eq(0) a").attr('href');
}
}
console.log(imglinks);
}
findimagelinks();
String concatenation is not right!
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
// ------------------------------------------^
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
// -----------------------------------^
Updated Snippet
function findimagelinks(){
var rows = jQuery(".sortable tr.even").length + jQuery(".sortable tr.odd").length;
var imglinks = [];
for (i = 0; i < rows; i++) {
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
if (conditionvalue == "some string") {
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
}
}
console.log(imglinks);
}
findimagelinks();
Your selector is wrong. Properly concatenate the strings like this
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
Then your code will look like,
for (i = 0; i < rows; i++) {
var conditionvalue = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(3)").text();
if (conditionvalue == "some string") {
imglinks[i] = jQuery(".sortable tr:eq(" + (i + 1) + ") td:eq(0) a").attr('href');
}
}
My loop function for my vowels counter in not working correctly and I don't know where I have gone wrong I would like some assistance with it.
I am trying to get the most used vowel to be bold so say I have A = 34 and E = 45 so E should be bold like this E
But I don't know whether I am missing some code or if I have got something wrong in my code.
This is my JavaScript.
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
// These are the counters for the program to find the vowels.
var countA = text.match(/[Aa]/g).length;
var countE = text.match(/[Ee]/g).length;
var countI = text.match(/[Ii]/g).length;
var countO = text.match(/[Oo]/g).length;
var countU = text.match(/[Uu]/g).length;
var countComma = text.match(/[,.!": ;?)(]/g).length;
var bold = "<strong>";
var vowels = new Array();
vowels[0] = "countA";
vowels[1] = "countE";
vowels[2] = "countI";
vowels[3] = "countO";
vowels[4] = "countU";
for (var i = 0; i < vowels.length; i++) {
document.getElementById("result").innerHTML = i + vowels[i] + "<br />";
}
// This code will output the results.
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + countU + "<br />";
document.getElementById("result").innerHTML += "Punctuation: " + countComma + "<br />";
}
This is my HTML.
<div style="text-align: center;">
<h1> Vowel Counter </h1>
Please enter text for your vowel count:
<br>
<textarea id="text" rows="10" style="width: 100%;"></textarea>
<br>
<button onclick="countVowels();">Count Vowels</button>
<p id="result"></p>
And this is my fiddle.
You seem to be getting the count right. So the only problems left I guess are:
Getting max count
Displaying it in bold
I referred to this to get max count, and then some tweaks to your code to get the max count displayed in bold.
var vowels = new Array ();
vowels [0] = {"vowel" : "A", "count" : countA};
vowels [1] = {"vowel" : "E", "count" : countE};
vowels [2] = {"vowel" : "I", "count" : countI};
vowels [3] = {"vowel" : "O", "count" : countO};
vowels [4] = {"vowel" : "U", "count" : countU};
var maxCount = Math.max.apply(Math, vowels.map(function(o) {
return o.count;
}));
for (var i = 0; i < vowels.length; i++) {
document.getElementById("result").innerHTML += (vowels[i].count == maxCount? "<B>" : "") + vowels[i].vowel + "'s: " + vowels[i].count + "<br />";
}
See this updated fiddle.
var result = "";
for(var i = 0; i < text.length ; i++){
if(text[i] == vowelsmustusedUpCase || text[i] == vowelsmustusedLowCase ){
result += "<strong>"+text[i]+"</strong>";
} else {
result += text[i];
}
}
document.getElementById("text").value = result ;
add this, but in textarea you can't see the bold
I think you should first find which is the most used vowel, and then compare it with the result line in your output. E.g.:
vowelCount = { A: countA, E: countE, I: countI, O:countO, U:countU };
// Find vowel with maximum appearances
var vowelMaxCount = -1;
var vowelMostPopular = -1;
for(vowel in vowelCount) {
if(vowelCount[vowel] > vowelMaxCount) {
vowelMaxCount = vowelCount[vowel];
vowelMostPopular = vowel;
}
}
// This code will output the results.
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
for(vowel in vowelCount) {
v = (vowel == vowelMostPopular)?"<strong>"+vowel+"</strong>":vowel;
document.getElementById("result").innerHTML += v+"'s: " + vowelCount[vowel] + "<br />";
}
document.getElementById("result").innerHTML += "Punctuation: " + countComma + "<br />";
Demo fiddle: http://jsfiddle.net/lparcerisa/a8n947kw/1/
Ok here's a code review/answer:
First I modified these lines:
var countA = text.match(/[Aa]/g).length;
To:
var countA = (text.match(/[Aa]/g) ? text.match(/[Aa]/g).length : 0);
As it returns "Uncaught TypeError: Cannot read property 'length' of null" if the vowel doesn't appear in the control. This will set's it to 0.
Next I simplified the array declaration to:
var vowels = ["countA", "countE", "countI", "countO", "countU"];
Then I removed this seciton, which does nothing as it's overwritten later:
// does nothing
// for (var i = 0; i < vowels.length; i++) {
// document.getElementById("result").innerHTML = i + vowels[i] + "<br />";
// }
Then I worked out the highest count using Math.max:
var maxVal = Math.max(countA,countE,countI,countO,countU);
Then to make the value bold in the output, I created a function to compare values to the max value:
function formatValue(val, max) {
return (val === max) ? '<strong>' + val + '</strong>' : val;
}
So your final section would call this function to output the number like this:
document.getElementById("result").innerHTML += "A's: " + formatValue(countA,maxVal) + "<br />";
Demo JS Fiddle
Complete JS
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
// These are the counters for the program to find the vowels.
var countA = (text.match(/[Aa]/g) ? text.match(/[Aa]/g).length : 0);
var countE = (text.match(/[Ee]/g) ? text.match(/[Ee]/g).length : 0);
var countI = (text.match(/[Ii]/g) ? text.match(/[Ii]/g).length : 0);
var countO = (text.match(/[Oo]/g) ? text.match(/[Oo]/g).length : 0);
var countU = (text.match(/[Uu]/g) ? text.match(/[Uu]/g).length : 0);
var countComma = (text.match(/[,.!": ;?)(]/gi) ? text.match(/[,.!": ;?)(]/gi).length : 0);
var bold = "<strong>";
var vowels = ["countA", "countE", "countI", "countO", "countU"];
var maxVal = Math.max(countA,countE,countI,countO,countU);
// This code will output the results.
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + formatValue(countA,maxVal) + "<br />";
document.getElementById("result").innerHTML += "E's: " + formatValue(countE,maxVal) + "<br />";
document.getElementById("result").innerHTML += "I's: " + formatValue(countI,maxVal) + "<br />";
document.getElementById("result").innerHTML += "O's: " + formatValue(countO,maxVal) + "<br />";
document.getElementById("result").innerHTML += "U's: " + formatValue(countU,maxVal) + "<br />";
document.getElementById("result").innerHTML += "Punctuation: " + countComma + "<br />";
}
function formatValue(val, max) {
return (val === max) ? '<strong>' + val + '</strong>' : val;
}
The following problem is causing me some headache. I'm building an application to compare transaction data with a list of tenants and what they're supposed to pay for rent.
I've got it running nicely except it compares EACH transaction with the monthly rent. What I want to do is first add all (relevant) transaction amounts per month and then compare them.
Should I just build another nested for-loop to compare all the transaction months before I run this loop? I could potentially drop in years of transaction data making it quite inefficient...
Any tips are greatly appreciated.
var table = "<table><thead><tr><th>Rek</th><th>Name</th><th>Date</th><th>Amount</th><th>Rent</th><th>Diff</th></tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < tenant.length; j++) {
if (tenant[j].reks.indexOf(data[i].rek) == -1)
continue;
else {
var diff = tenant[j].rent - data[i].amount; //TODO monthly!!!
var style = " style='background-color: ";
if (diff > 0)
style += "red;'";
else
style += "green;'";
table += "<tr><td>" + data[i].rek
+ "</td><td>" + data[i].name
+ "</td><td>" + (data[i].date.getMonth() + 1) + "-" + data[i].date.getFullYear()
+ "</td><td>€ " + data[i].amount
+ "</td><td>€ " + tenant[j].rent
+ "</td><td" + style
+ ">" + diff
+ "</td></tr>";
}
}
}
table += "</tbody></table>";
$('#top').html(table);