Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});
Related
I have a game I created that will add questions missed to my array missedArr, in my JSFiddle example, I have 2 buttons (both set to be wrong answers). After clicking these, it seems to have stored both clicks correctly, however I want give a readout at the end of the game to show my user what parts they did well on vs ones they did poorly on.
To do this, I created a function called determineScorecard which should serve to create a dict of my missedArr, however, when it goes to trigger I get undefined.
The dSc function should be sorting across the data-category set on the html buttons, then I want to console.log only the ones that were missed in category-2
function determineScorecard (){
//build dictionary for missed questions
var sortedMissed = {};
for( var i = 0, max = missedArr.length; i < max ; i++ ){
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}
sortedMissed[missedArr[i].category].push(missedArr[i]);
}
console.log(sortedMissed["2"]);
}
I can't seem to get this to split up correctly.
I think this is what you're trying to do:
var incorrect = [];
$('.answer').click(function(){
var data = $(this).data(),
correct = data.correct;
if(!data.correct){
incorrect.push(data);
determineScorecard();
}
});
function determineScorecard(){
var missed = {};
for(var i = 0, max = incorrect.length; i < max ; i++){
var question = incorrect[i];
if(!missed[question.category]){
missed[question.category] = [];
}
missed[question.category].push(question);
}
console.log(missed);
}
DEMO
However, I don't see how this can produce what you're expecting. The scorecard logic makes zero sense to me (with the code that's been provided). Can you post a complete example with the questions so we can see the entire flow?
Maybe you want something like this?
var missedArr = [];
$('.answer').click(function(){
var da=$(this).data();
if (da.correct) return false;
missedArr.push(da);
determineScorecard();
});
function determineScorecard (){
var sortedMissed = {};
$.each(missedArr,(i,da)=>{
if( sortedMissed[da.category] === undefined ){
sortedMissed[da.category] = [];
}
sortedMissed[da.category].push(da);
})
console.log(JSON.stringify(sortedMissed));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="btn btn-danger answer" data-category="2" data-question="2" data-value="300" data-correct="false">Google</button>
<button class="btn btn-danger answer" data-category="3" data-question="2" data-value="300" data-correct="false">Full-circle reporting</button>
In my solution I have not stored the whole buttonDOM elements but only their data()-objects into the sortedMissed array since these contain all the information about the question and button pressed. But if you don't like it, feel free to change that back again ...
Referencing your JSFiddle: The missedArr array contains DOM elements. To get the category, value, etc of that element you'll need to access the dataset property of the element.
missedArr[i].category // doesn't exist
missedArr[i].dataset.category // should exist
Updated for jQuery, which uses the .data() method:
missedArr[i].data('category') // should exist
When wrapping 'this' in the jQuery function like $(this), the element becomes a jQuery object, so to access the dataset use the .data() method rather than trying to access the properties directly like you would with vanilla JS:
// lines 22 - 24 of your JSFiddle
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}
I have an array in js containing multiple clickable items. When I click any of them, I want to change the contents of other divs to show the corresponding name and description. I now use something like this:
window.addEventListener("load",function(){
var displayName = document.getElementById("display-title");
var displayDesc = document.getElementById("display-desc");
var projectNames = ["Name1", "Name2"];
var projectDescs = ["Example project 1", "Example project 2"];
var projectButtons = [document.getElementById("project-One"), document.getElementById("project-Two")];
for(var i = 0; i < projectButtons.length; i++){
projectButtons[i].addEventListener("click", function(){
displayName.innerHTML = projectNames[i];
displayDesc.innerHTML = projectDescs[i];
});
}
});
However when I click any of the buttons I always get the second name and description showing. How would I go about making it change to the selected button? In the final thing, I'm changing more than just the name and description, and I will be adding many more buttons in the array, so making different functions for each button isn't really an option, and I'm limited to using Javascript, so JQuery or PHP isn't an option. I'm probably missing something obvious, but I have no idea what...
EDIT:
The following seems to work, which is what was answered already, although I'm not sure if I've implemented it correctly:
for(var i = 0; i < projectButtons.length; i++) {
(function(i) {
setTimeout(function() {
projectButtons[i].addEventListener("click", function(){
displayName.innerHTML = projectNames[i];
displayDesc.innerHTML = projectDescs[i];
});
});
})(i);
}
This is the infamous closure variable in loop
http://www.teknically-speaking.com/2013/01/closures-in-loops-javascript-gotchas.html
I have a problem with define a second class in one Var
Here is the Code: http://jsfiddle.net/2DuQc/
How can I make work this fine?
It's written in JQuery!
var animateEye = $('.rightEye, .leftEye');
doesnt work!
Actually your code won't work because you are overwriting your variabile with only one selector .leftEye so the .rightEye will not have nothing attached to it.
You can use a multiple selector than loop through the result using jQuery each and apply yuor current code.
Use the same class as inner element and find it as a children of the current element.
Code:
$('.rightEye, .leftEye').each(function () {
var animateEye = $(this);
var eyes = animateEye.find(".Eye");
Demo: http://jsfiddle.net/IrvinDominin/rU9E2/
var animateEye = $('.rightEye, .leftEye');
This will give you an array of items, so when you call, say, animateEye.offset(), which one is it supposed to choose? It'll bomb out.
Your current code:
var animateEye = $('.rightEye');
var eyes = $(".Eye");
var animateEye = $('.leftEye');
This will obviously always use .leftEye.
My suggestion? Loop through rightEye and leftEye like so:
var eyes = $('.rightEye, .leftEye');
for(var i = 0; i < eyes.length; i++) {
var animateEye = eyes[i];
}
I'm trying to load X amount of <li>'s into a <ul> via a for loop in a jquery function, and while I think I've got the syntax about right I'm not getting anything loading. (no problem with loading a single <li>, but none for multiples with the method I've tried)
Initially I attempted to pass a variable into the loop to determine the amount of increments: var peekListAmount = 5;
That didn't work so I went for a bog-standard loop incrementer. That doesn't work either so, after searching here and getting close, I have put together a fiddle to see if someone can point out what I'm doing wrong: http://jsfiddle.net/janowicz/hEjxP/8/
Ultimately I want to use Knockout.js to dynamically input a number to pass to the loop amount variable, but 1st things 1st.
Many thanks in advance.
When you do:
var peekListItem = $('<li>...</li>');
you're creating a single instance of an <li> node, encapsulated in a jQuery object.
Appending an already-present node to the DOM just removes it from its current place in the DOM tree, and moves it to the new place.
You need to create the node inside the loop, not outside, otherwise you're just re-appending the same node each time, not a copy of that node.
In fact, given you're not manipulating that node, you can just put the required HTML directly inside the .append() call without wrapping it in $(...) at all:
$(function() {
var peekList = $('<ul class="peekaboo-list">').appendTo('div.peekaboo-wrap');
function addLiAnchorNodes(nodeAmount) {
var html = '<li>' +
'<p class="peekaboo-text"></p></li>';
for (var i = 0; i < nodeAmount; ++i) {
peekList.append(html);
}
}
addLiAnchorNodes(5);
});
See http://jsfiddle.net/alnitak/8xvbY/
Here is you updated code
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
var peekListItem = '<li><p class="peekaboo-text"></p></li>';
//var peekListAmount = 5;
var tmp = '';
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
tmp += peekListItem;
}
peekList.append(tmp);
$('div.peekaboo-wrap').append(peekList); // This bit works fine
}
addLiAnchorNodes();
});
This should work. Instead of appending the list item in each loop, append the list only once at the end.
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
peekList.appendTo('div.peekaboo-wrap');
var addLiAnchorNodes = function (nodeAmount){
var list = "";
for (var i = 0; i < 10; i++){
list += '<li>Sample<p class="peekaboo-text"></p></li>';
}
peekList.append(list);
}
addLiAnchorNodes();
});
Here is the updated fiddle
Try this:
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
$(peekList).appendTo('div.peekaboo-wrap'); // This bit works fine
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
var peekListItem = $('<li><p class="peekaboo-text"></p></li>');
peekListItem.appendTo(peekList);
}
}
addLiAnchorNodes();
});
I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.
Here is the input code:
<input type="number" id="id_[SOME_ID_HERE]" value="0">
and the loop used to update the values.
for (var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(3)).value = 5;
}
jsfiddle: http://jsfiddle.net/zkTud/
EDIT: Seems like it doesn't work with type="text" as well...
EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.
Thanks anyways!
I really appreciate the help I'm getting in this site! :)
The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(5)).value = 5;
}
Here's an updated fiddle.
The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.
Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):
document.getElementById("i" + val.substring(3)).value = 5;
demo http://jsfiddle.net/bY4EV/6/
sustring(3) gives d_1 : How to substring in jquery
hope this helps
code
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id_" + val.substring(5)).val("5");
}
Check this, JSFiddle , Updated and corrected your problem.
Code:
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id" + val.substring(4)).val( "5");
}