collect data by id using javascript - javascript

I have to save temporary data for my webpage using java script.This is the way that i save i one by one since the data is an array.
var product= new Array();
product[1] = document.getElementById("product[1]").value;
product[2] = document.getElementById("product[2]").value;
This method is working. but when i run it by looping, it doesnt work.
for(var i=1; i < no_item; i++){
product[i] = document.getElementById("product[i]").value;
}
*product[] is a varibale that I take from a html dropdown menu
Can anyone please tell me the problem ? thanks ~ =)

Should be written as, as you are going to be getting the id "product[i]" every time with your original code. This will get "product[1]" then "product[2]" and so on:
for(var i=1; i < no_item; i++){
product.push(document.getElementById("product[" + i + "]").value);
}
Also, as a comment, we tend to prefer var product = []; over var product = new Array(); in javascript but both will work.

Related

Error saving this JS in WSO2-Integration Studio

I use Integration Studio,
and I have always used inside my Xml files js script,
But this time I still get an error saving this inline JS, and I really can't understand the reason of this error.
<script language="js"><![CDATA[var elements = mc.getProperty('elementsFromJson');
var payload = [];
for(let i = 0; i <= elements.length; i++){
var id= elements[i].id;
var type= elements[i].type;
var couple= {"id":id ,"type":type};
print(couple);
payload.push(couple);
}
var payloadFinale = {payload};
print('result in JSON: ' + payloadFinale);
var data= mc.setPayloadJSON(payloadFinale);]]></script>
So would be great your help in case you use Integration studio as me,
thank you for your time.
You have issues in the following lines.
for(let i = 0; i <= elements.length; i++){
Here change let => var
var payloadFinale = {payload};
The above syntax is wrong, not sure what you are trying to achieve here. Probably, you can remove the above line, when you do mc.setPayloadJSON it would be saved as a proper JSON.

get params from a js function from a webpage

I'm trying to retrieve automatically some element onto a webpage, but I'm stuck with multiple things.
First I'm looping through all the classes named with the help of document.getElementsByClassName('trList') that got the informations that i need.
Then into the multiple results i'm trying to extract the parameters contained in this :
<div id="action_0" onclick="cba.facture.controllers.factureListeController.createFactureListeTooltipActionDialog('73039508',
'action_0_TooltipDialog',
'action_0',
'190px', 'Télétransmise', '1', 'false', '0',
'7622', '14902', 'Télétransmise', '')" onmouseover="dijit.Tooltip.defaultPosition = ['above', 'below']">…</div>
I'm trying to get the 1st and 9th parameters of the onclick function.
And of course there are several iteration of this function in the results listed by the GetelementsByClassName.
I really don't have any clue on how to do this.
Could someone give me some direction on how to retrieve this?
Edit :
Trying to use the answer given earlier by #adriano009
i've got two problems :
First, the LET scope creates a bug in safari, telling me that i "can't create duplicate variable that shadows a global property”; so i'm using VAR for this one.
Second, with this code :
jsScript +="var slides = document.getElementsByClassName('trList');";
jsScript +="for (let i = 0; i < slides.length; i++) {";
jsScript += "let attr = slides[i].getAttribute('onclick'); ";
jsScript +=" console.log(attr);";
jsScript +="};";
Even though there are onclick attributes listed in slides.item(i), the log shows that it founds 0 attributes while trying to get them with slides[i].getAttribute('onclick'). Why's that?
let all = document.getElementsByClassName("class_name");
for (let i=0, i < all.length; i++) {
let attr = all[i].getAttribute("onclick");
let first_param = attr.split[','][0];
let ninth_param = attr.split[','][8];
console.log(first_param, ninth_param);
}

For loop within a for loop? - Javascript

newbie javascript question. I made sure to research as much as I could before posting here, I've tried many solutions but could be searching for the wrong thing.
I've attached an image below of the issue I have. I'm trying to retrieve everything in the dark blue boxes, but I can't identify those input tags as there is nothing unique about them, I can however identify their parent divs by the class 'f-active'. When the divs have that class they have been selected by the user which is what I am interested in.
My attempt so far
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var i=0; i < childArray.length; i++){
if(childArray[i].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[i].name);
// console.log(catNameCollection);
}
}
}
I tried to use a for loop to get all the parents, then use another for loop to select the children (input tags) and then grab the name attribute, however it is just outputing numbers. I did originally try to create 'divArray' as document.querySelectorAll('div.add-filter.f-active').children, but this and then grab the name attribute in the for loop, but this didn't return anything at all.
Any help anyone could offer would be greatly appreciated, I'd love to know what I'm doing wrong.
Thank you!
Your i is same for both loops. Use:
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var k=0; k < childArray.length; k++){
if(childArray[k].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[k].name);
// console.log(catNameCollection);
}
}
}
Classic for-loops usually aren't the best tool for iterating through DOM elements - they add a lot of clutter and are error-prone, especially when you have to nest them.
In your case it'd be simpler to instead modify your query to directly grab all input elements with a div.f-active parent, then extract the names by iterating through them with a forEach. For example (using ES6 or higher):
const arr = [];
// Get list of all <input> elements that have <div> element parents with class f-active.
const nodes = document.querySelectorAll('div.add-filter.f-active > input');
// Extract name from each input element matched by your selector.
nodes.forEach(node => arr.push(node.name));
Or if you're stuck using ES5:
var arr = [];
var nodes = document.querySelectorAll('div.add-filter.f-active > input');
nodes.forEach(function(node) {
arr.push(node.name);
});
Here's a quick JSFiddle I put together to demonstrate the concept for you. (You'll need to open the console to see the result)
Hopefully that helps :)

number of xml attributes->javascript multi array->function / process

I have comments in a database relative to each post. It pulls the post and all comments according to that post in one query, and groups them inside an XML node. I get the amount of attributes in each node, and take away the standard number of attributes that every post has by default, and that leaves me with the number of comments.
The comment structure is as follows:
comment0 Hey nice post!
commentdate0 2014-12-1 08:25:02
commentaudthor0 Chris
comment1 cool!
commentdate1 2014-08-2 09:25:02
commentaudthor1 Jason
and so on, the comments increase by that number.
So I need to check how many comments there are (done) and then retrieve them from the xml node (using $(this).attr('comment'+i)) Where i would be the counter (comment0, comment1 and so on)
Here is my current code to get it into the array:
var comms = new Array();
var count = this.attributes.length;
var av = count-11;
if(av != 0) {
for(var i=0; i<av; i++) {
for(var j=0; j<2; j++){
comms[i][j] = $(this).attr('comment'+i);
comms[i][j+1] = $(this).attr('commentdate'+i);
comms[i][j+2] = $(this).attr('commentauthor'+i);
}
}
}
But it is giving me the following error:
Uncaught TypeError: Cannot set property '0' of undefined
Now, how can I load it into a multi dimensional array to store the data, pass it to a function, and then process each row separately?
ie: this is what I am trying to do:
Array {
'comment1':
comment
commentdate
commentauthor
'comment2':
comment
commentdate
commentauthor
}
and then how would I be able to process each comment inside the function? ie: with each comment, do this.
Thanks in advance!
You need to create the inner array before adding to it. Try this:
var comms = new Array();
var count = this.attributes.length;
var av = count-11;
//if(av != 0) { // I commented this condition out, as it is not needed here
for(var i=0; i<av; i++) {
comms[i] = []; // Create a new array here before adding to it (this syntax is more common than the longer "new Array()" syntax you used
comms[i][0] = $(this).attr('comment'+i);
comms[i][1] = $(this).attr('commentdate'+i);
comms[i][2] = $(this).attr('commentauthor'+i);
}
//}

How to get the next element of an array with Jquery onclick

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;
});

Categories