How to pass value to using external variable in javascript? - javascript

following code works properly
draw([['Rice',20,28,38],['Paddy',31,38,55],]);
but when i try using external variable like
var val1=20;
var val2=30;
var val3=40;
draw([['Rice',val1,val2,val3],['Paddy',31,38,55],]);
It wont work.

Just showing that your example code works fine using the Firebug console. Can you post more of your code? Your stripped-down example is probably missing something else that's causing a problem.
What is your draw() function doing? Could something in that function be breaking?
EDIT: Another problem could be the trailing comma after your second array. That will throw an error in Internet Explorer.
alert([['Rice',val1,val2,val3],['Paddy',31,38,55],]);
should be:
alert([['Rice',val1,val2,val3],['Paddy',31,38,55]]);
That may solve your issue (though you also have that in your 'working' example, but I thought it worth mentioning).

Your code snippets are not equivalent -- the second one has different values (['Rice',20,30,40] vs ['Rice',20,28,38]). Other than that, they are equivalent and should have the same effects.

Related

correct js in tag manager

i am trying to add a tag (to custom javascript) to my google tag manager, but i get "Error at line 12, character 5: Parse error. primary expression expected". Can i please get help to correct my code?
<script>
var x=document.getElementById("ad"),
z=window.getComputedStyle(x,null),
y=z.getPropertyValue("display");
function showAdblockAlert()
{alert("You're missing ads, therefore turn off your AD-blocker!")
}function adBlockNotDetected()
{alert("Thank you for not using AD-blocker");
console.log
("no ad-blocker")}console.log(y);
"none",
==y?showAdblockAlert():adBlockNotDetected();
</script>
This code is odd. It combines some basic mistakes as well as advanced techniques if you can call that a ternary or using commas with a var.
Anyhow, your error is likely due to poor copying. The "none",== part, I think, got there from somewhere else.
Here, try this:
var x = document.getElementById("ad"),
z = window.getComputedStyle(x, null),
y = z.getPropertyValue("display");
function showAdblockAlert() {
alert("You're missing ads, therefore turn off your AD-blocker!")
} function adBlockNotDetected() {
alert("Thank you for not using AD-blocker");
console.log("no ad-blocker")
}
console.log(y);
y ? showAdblockAlert() : adBlockNotDetected();
You should know, however, that alerts in production is a very good way to get your site blacklisted one way or another.
Besides, declaring globals like that is a very bad idea.
Your code is unsafe. It relies on getComputedStyle to be there, as well as other elements. It throws errors otherwise.
Finally, the use of functions there seems to be a little excessive. They're not needed if you swap the ternary with a normal if, making the code much more readable.

Does this kind of value setting work in Javascript?

I'm trying to create code that requires the least number of bytes and that works for all browsers including IE 7.
In this example, the program calls dosomething('x1') and dosomething('x2').
If I have code like this:
var items,item,index,count;
items=Array('x1','x2');
count=items.length;
for (index=0;index<count;index++){
item=items[index];
dosomething(item);
}
Could I reduce it to this and have it still function exactly the same in all browsers:
var a=Array('x1','x2'),c=a.length,i;
for (i=0;i<c;i++){
f(a[i]);
}
I understand I changed the variable names and calling function name but my goal is to use the least number of bytes possible in the code to make the code execute.
I'm just not sure if declaring a variable equal to a property of a value from a previous variable in the same list of declarations would actually return correct results.
In other words, does var a=Array('x1','x2'),c=a.length... work, or do I have to specifically do var a=Array('x1','x2');var c=a.length; to make it work in all browsers including IE 7?
This is what the Google Closure Compiler service returned:
var a,b,c,d;a=["x1","x2"];d=a.length;for(c=0​;c<d;c++)b=a[c],dosomething(b);
You can find many different Javascript compressors online to automate the process you are hand coding now. Yet, it's always good to understand how they work as it helps to write code that is better compressed.
As for IE, you can test your code by changing the emulations settings in the IE debugger panel. Just press F12, click the Emulation tab, and adjust the document mode to 7 (IE7).
Hope this is enough to get you started in the right direction.
You can use Array.map from IE 9
var items = Array('x1','x2');
items.map(dosomething(item));

Using MVC resource in Jquery - function stops working

I have a Jquery function in MVC View that check if at least one checkbox is clicked. Function is working properly if I use hardcoded string. But when I add
#Resources.myString into, it stops working, I can't figure out why
$('.form-horizontal').on('submit', function (e) {
if ($("input[type=checkbox]:checked").length === 0) {
e.preventDefault();
alert("This is working");
alert(#Resources.myString); //with this the function is not working anymore
return false;
}
});
I need to add the the string for multilingual purpose.
I tried diferent aproches
alert(#Resources.myString);
alert(#Html.Raw(Resources.myString))
var aaa = { #Html.Raw(Resources.myString)} //and calling the aaa
I think I am missing some basic knowlage of how this should work together
During page rendering, #Resources.myString will be injected as is in the code. For instance, if myString == "abc";, you'll end up with alert(abc); which is not what you want.
Just try to enclose your string in quotes:
alert("#Resources.myString");
As an aside, putting Razor code in Javascript logic is usually considered bad practice, as it prevents you from putting Javascript code in separate files (and therefore caching), and makes the code less readable.
Take a look as this question and the provided answer which gives a simple way to deal with that.
As ASP.NET dynamically generates HTML, CSS, JS code, the best way to find the error is to read the generated sources (Ctrl + U in most modern browsers).
You will see that your code
alert(#Resources.myString);
produces
alert(yourStringContent);
and should result in a console error yourStringContent is not defined.
You need to use quotes as you are working with a JavaScript string:
alert('#Resources.myString');
It will produce a correct JavaScript code like:
alert('yourStringContent');

NaN error when trying to add variables

when i run this with the rest of my code everything works fine except this! i just get something saying £NaN0 i dont understand why it is not a number someone please help!
Your code that you posted is fine, but the code you haven't posted is not.
I ran your code with the blueprint/VPS stuff commented out, and it worked just fine. I'm guessing your problem is here:
var userChoiceBlueprntVal = blueprtSelected.options[blueprtSelected.selectedIndex].value;
var userChoiceBlueprntValint = parseInt(userChoiceBlueprntVal);
What are you getting for userChoiceBlueprntVal? More than likely it is not an int, which makes userChoiceBlueprntValint NaN, and subsequently all the rest of your calculations.
If you can't fix it from here, post all of your code.

Passing Alphanumeric Parameter to javascript function

when i call a javascript function say, onclick="doSome(this.value)" where this.value=123, it works fine.
But if i call onclick="doSome(this.value) where this.value=A123, it is not working. How to rectify this problem?
I was also facing the same issue. I had to call a function with a product code as a parameter . It was working when the product code is numeric and it was not working for products like "AE11002".
I fixed the problem by changing the method invocation from
onClick="decreaseQuantity(${product.code})" to onclick='decreaseQuantity("${product.code}")'.
I think this will help you also. Please try this.

Categories