I need to update length variable that was defined in imacros js in macro.js. I have tried different code but not able to pass information from imacros(js on page) to imacro.js (js of imacro);
for example;
var lenght = 0;
iimPlay("CODE:URL GOTO=JAVASCRIPT:var<SP>len=window.document.getElementById('table1').getElementsByTag('tr');");
now how to pass that inner len variable info to outer length variable. i need to run a loop based on length.
I can pass info from JS part to Imacros part with iimSet('var',var); is there any way I can update JS variable's value inside imacros code.;
Here is a trick with an ‘alert’ dialog:
var length = 0;
iimPlay("CODE:URL GOTO=JAVASCRIPT:alert(window.document.getElementById('table1').getElementsByTag('tr').length);");
length = parseInt(iimGetErrorText().match(/Dialog message: "(.*)",/)[1]);
Related
I want an easy way to set a variable value equal to n when function(n) runs.
Hovedkort
Prosessor
Arbeidsminne
I have this piece of HTML code. And I want the loadProdType function to change the value of a variable prodCat according to loadProdType's value. I tried the code under with and witout localstorage.setItem(loadCat, j). The js document is linked and there are no linking errors cause other pieces of code runs as it should.
var loadCat = 0
function loadProdType(j){
loadCat = j}
How can I set loadCat's value equal to loadProdType's value/parameter.
Thanks in Advance.
Edit:
Unsure how to set local storage for this but what I want the code to do is the following:
Change the value of variable prodCat according to the value of the onclick function.
Redirect to: products.html
When in products.html I run a piece of code that uses the prodCat value to choose a spesific index in an array.
All in all I just need to be able to change prodCat on one page(to the value of a funcion or with a onclick) and have it saved on the next.
Last edit
I'll create different functions for each onclick and try that with local storage.
You need either ? in the URL or local storage.
?
In main document:
location.href = "products.html?prodType=" + loadCat;
In products.html:
var loadCat = new URL(document.URL).searchParams.get("prodType");
localstorage
In main document:
window.localStorage.setItem("prodType", loadCat);
In products.html:
var loadCat = window.localStorage.getItem("prodType");
I am declaring some variables in a function and their values get updated within the for loop. At the end of the function I want to see the final values of some of these variables.
After spending a whole day on why what I want is not happening, I am posting the function here to get some insight.
In the function you can see two alerts - the first runs with each iteration of the for and gives me the current values of the variables. I do not want this alert but have inserted it here just to show that the code does actually do what I want it to do within the for loop.
What I want is only the last alert.... BUT for some reason it never appears!
As I understand it, if a variable has been declared at the beginning of a function, its value can be accessed right up till the end... If this is correct, why does the last alert not appear?
NOTE: This code is being run on a MsWord generated html, which contains innumerable unnecessary span tags that I need to remove before I can use the contents for documentation purposes. Not being able to get these values is what is preventing me from finalizing a small tool I plan to use to convert about 400 MsWord pages for a project!
function uponetag()
{
var spank=document.getElementsByTagName('span'); //look at all span tags
var spann=spank.length; //number of span tags on the page
var yes=0;
var no=0;
for (i=0; i<=spann; i++)
{
var spancont=spank[i].innerHTML;
//get the parent node
var outer = spank[i].parentNode;
outertag=outer.tagName.toLowerCase();
//get the inner html of the parent node
var outercont=outer.innerHTML;
//create a string manually placing the opening and closing span tags around the current span content
var compareit=("<span>"+spancont+"</span>");
//compare the manual string to inner content of the parent node
if (outercont===compareit)
{
//replace the inner html of the parent node with the current span content
outer.innerHTML=spancont;
yes=yes+1;
}
else
{
no=no+1;
}
alert ("Converted = "+yes+"\n\n Not converted = "+no); //this alert works
}
alert ("The page originally had "+spann+" span tags. \n ON EXIT: Converted = "+yes+"\n\n Not converted = "+no);
//THIS ALERT DOESN'T!!! WHY?????
}
I have tried all the changes (i=spannum, var1=.... etc) suggested here without any success! In fact, while doing this, I found that though there are 49 spans in the original page, the script throws the error in the firebug console after 29 runs (20 yeses and 9 nos).
The code read beyond the length of the array, causing an error.
That's why the loop alerts fire but the final alert outside the loop does not fire.
This loop
for (i=0; i<=spann; i++)
includes i=spann, which is 1 beyond the end.
I think you meant to use
for(i=0;i<spann;i++)
which is correct.
I should also note that Javascript does not have block-level variables. It has function-scoped variables. Declaring a var in a for loop block is the same as declaring the var at the initialization of the current function (called hoisting) and setting it in the loop.
for (i=0; i<=spann; i++)
//change it to :
for (i=0; i<spann; i++)
Iam using Google Tag manager==GTM as well as Visual Website Optimizer==VWO. All the script tags for both application are implemented accordingly.
In order to be able to track revenue we have to save the transactionTotal of an order into a variable that VWO uses to count the conversion rates on a specific test. The VWO clicks and visits are counted correctly but not the conversion.
I have created a macro in GTM ({transactionTotal}) based on fetching the data.
First I get all the meta tags where we have the ecommerce values.
var metaObj = {}, m = document.getElementsByTagName('meta'), i = m.length; //scope expanded from only .head
while (i--) { // looping down will result in the same behaviour as stopping # 1st
metaObj[m[i].name] = m[i].content;
}
Then push the meta value in the dataLayer
dataLayer.push({'transactionId': metaObj['WT.tx_i']});
In GTM I created a macro
in the confirmation page:
//should be the value of the order total
var _vis_opt_revenue = ({transactionTotal});
This returns an error and no value is save in this variable.
Any ideas or help is much appreciated.
Could you indent your code please ? It will be much easier.
Secondly, you use a macro that is looking for
transactionTotal
and you push on dataLayer an object named
transactionId
Therefore, it could not work
I figured out I had a syntax error user parenthesis instead of curly brackets
so it should be
var _vis_opt_revenue = {{transactionTotal}};
instead of
var _vis_opt_revenue = ({transactionTotal});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript infamous Loop problem?
I am having a small issue, and it would be very nice if some of you could realize about what kind of logic is missing here, since I cannot seem to find it:
I have an array with the results of some previous operation. Let's say that the array is:
var results = [0, 1];
And then I have a bunch of code where I create some buttons, and inside a for loop I assign a different function to those buttons, depending on the position of the array. The problem is that for some reason, all the buttons created (two in this case) come out with the function assigned to the last value of the array (in this case, both would come out as one, instead of the first with 0 and the second with 1)
This is the code:
for (var i = 0; i < results.length; i++) {
var br2 = b.document.createElement("br");
var reslabel = b.document.createTextNode(Nom[results[i]].toString());
var card = document.createElement("input");
card.type = "button";
id = results[i]; // this is the problematic value.
card.onclick = newcard; // this function will use the above value.
card.value = "Show card";
divcontainer.appendChild(br2);
divcontainer.appendChild(reslabel);
divcontainer.appendChild(card);
}
As it is, this code produces as many buttons as elements in the array, each with its proper label (it retrieves labels from another array). Everything is totally fine. Then, I click the button. All the buttons should run the newcard function. That function needs the id variable, so in this case it should be:
First button: runs newcard using variable id with value 0
Second button: runs newcard using variable id with value 1
But both buttons run using id as 1... why is that?
It might be very simple, or maybe is just that in my timezone is pretty late already :-) Anyways, I would appreciate any comment. I am learning a lot around here...
Thanks!
Edit to add the definition of newcard:
function newcard() {
id = id;
var toerase = window.document.getElementById("oldcard");
toerase.innerHTML = "";
generate();
}
the function generate will generate some content using id. Nothing wrong with it, it generates the content fine, is just that id is always set to the last item in the array.
Your id is a global variable, and when the loop ends it is set to the last value on the array. When the event handler code runs and asks for the value of id, it will get that last value.
You need to create a closure to capture the current results[i] and pass it along (this is a very common pitfal, see Javascript infamous Loop problem?). Since newcard is very simple, and id is actually used in generate, you could modify generate to take the id as a parameter. Then you won't need newcard anymore, you can do this instead:
card.onclick = (function(id) {
return function() {
window.document.getElementById("oldcard").innerHTML = "";
generate(id);
};
}(results[i]));
What this does is define and immediately invoke a function that is passed the current results[i]. It returns another function, which will be your actual onclick handler. That function has access to the id parameter of the outer function (that's called a closure). On each iteration of the loop, a new closure will be created, trapping each separate id for its own use.
Before going on, a HUGE thank you to bfavaretto for explaining some scoping subtelties that totally escaped me. It seems that in addition to the problems you had, you were also suffering from scoping, which bit me while I was trying to craft an answer.
Anyway, here's an example that works. I'm using forEach, which may not be supported on some browsers. However it does get around some of the scoping nastiness that was giving you grief:
<html>
<body>
<script>
var results = [0,1];
results.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = "Show card";
document.body.appendChild(card);
});
function newcard(x) {
alert(x);
}
</script>
</body>
</html>
If you decide to stick with a traditional loop, please see bfavaretto's answer.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic object property name
I have an object like this
var localAppConfig = {
wallet:0,
paySomeone:0,
payBills:0,
accounts:0,
moveMoney:0,
alerts:0,
offers:0,
checkIn:0
};
I want to set value 1 for particular elements within this localAppConfig
Which element needs to be set is retrieved from the json - which arrives from the server.
say, I want to set value = 1 for wallet, paySomeone, payBills, alerts, offers, checkIn
These are retirved from the json like
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = eval('localAppConfig.'+name);
eval('localAppConfig.'+name)=1;
}
var name contains name of the element and I am able to access its value correctly,
How can I set the value using javascript?
I tried accessor=1 but its not working.
Thanks :)
Anyhow: try this on for size:
localAppConfig[name] = 1;//where name is a variable of choice, it's value will be used as the propertyname
And again:
-When all you have is the eval hammer, everything looks like your thumb.
–Brendan Eich in response to: we should encourage use of eval() rather than the Function constructor for dynamic creation of functions.
But why use a list of the properties? you might as well use a for...in loop: in case of objects, like yours, it's perfectly all right. As long as you check .hasOwnProperty, too:
for (var prop in localAppConfig)
{
if (localAppConfig.hasOwnProperty(name))
{
//set, delete... do whatever
}
}
You should do this instead:
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
Try localAppConfig[name] = 1;
It's just a javascript object, no need to use eval() on it.
Don't use eval(). You can add a property by referencing the index of that value within your object. If it doesn't exist then it will be created, otherwise the value will be overridden.
Try the following instead:
// localAppConfig[list[i].handle] = 1;
for(var i=0;i<len;i++){
localAppConfig[list[i].handle] = 1;
}
Or if you intend to reference the variable in another place then set a variable with the value of list[i].handle:
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
}