Access array value from function - javascript

I simply want to access the value of array status from another function. However, the alert is giving me value as undefined. Here's my code:
Test.php:
<html>
<body>
<script>
var status=[];
status[0]='1';
calculateInput();
function calculateInput(){
alert(status[0]);
}
</script>
</body>
</html>

You are colliding with window.status:
function calculateInput () {
alert( status === window.status ); // true
}
To avoid this, rename your array or get out of the global scope:
(function IIFE () {
var status = [];
status[0] = "1";
calculateInput();
function calculateInput () {
alert( status[0] );
}
}());

Change your variable name from status to something else
ex.
<html>
<body>
<script>
var mystatus=[];
mystatus[0]='1';
calculateInput();
function calculateInput(){
alert(mystatus[0]);
}
</script>
</body>
</html>

Related

Uncaught ReferenceError: AddAnime is not defined at HTMLInputElement.onclick (AnimeSite.html:51)

I'm making a quick site with a list and I can't call a function:
function:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
function AddAnime() {
var newItem = document.getElementById("div")
newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
</script>
</head>
But when I call it with this:
<input type="button" value="Add Anime" onclick="AddAnime();">
By the way, this is line 51
the error comes up.
I don't know what to do.
You need to expose the function outside of the onload scope:
<script>
function AddAnime() {
var newItem = document.getElementById("div") newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
window.onload = function() {
AddAnime();
}
</script>

Javascript - Share Variables over different <script> tags

I have one test.html file with two <script> tags. I need to share a variable from one to another..
Sample code:
<script type="text/javascript">
var test = false;
function testing() {
test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
The output is always:
I am inside..
failed
I also tried to use the window class but it doesn't matter.. (window.test)
What I have to do to get the 'working' alert?
Thanks if anyone can help me. I saw some similar questions, but the answers wasn't a solution for me.
EDIT:
The original code (simplified):
<head>
...
<script type="text/javascript" src="detectblocker.js"></script>
<!-- GitHub: https://github.com/sitexw/BlockAdBlock/ -->
...
</head>
<body>
<script type="text/javascript">
var blocker = false;
function adBlockDetected() {
blocker = true;
alert('inside');
}
if(typeof blockAdBlock === 'undefined') {
adBlockDetected();
} else {
blockAdBlock.onDetected(adBlockDetected);
}
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
</script>
<div class="header">
...
</div>
<div class="content_body">
<div class="requirs">
<ul>
...
<script type="text/javascript">
if (blocker == true) {
document.write("<li>enabled!</li>")
} else {
document.write("<li>disabled!</li>")
}
</script>
...
</ul>
</div>
</div>
...
</body>
The output is an alert() "inside" and the <li> "disabled".. (Blocker is enabled..).
The only difference I can see is on the end of the first <script> tag:
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
So why the snippet is working and my code not? Confusing...
If you do not use var before a variable it becomes a global variable like
test = true;
The variable test will be true during the page and also in your next scripts and functions.
Try this:
<script type="text/javascript">
var test = false;
function testing() {
var test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
There are two ways of doing it.
1) create a hidden element and set your variable from your first script to attribute of that element.
This is your hidden element
<input type="hidden" id="hiddenVar"/>
and can set it in javascript as
document.getElementById("hiddenVar").setAttribute("myAttr",test)
Now you can get it in next script as
document.getElementById("hiddenVar").getAttribute("myAttr")
2) By .data() you can read about it here

Passing a variable as reference to javascript/jquery function

I have a function called pages and i want to pass a variable selectively by not repeating the code again, is this possible?
old code
<script>
var pages= (function() {
var config = {
$config1: $( '#block1'),
$config2: $( '#block-bottom1')
};
//more codes
})();
</script>
This was my attempt
<script>
var pages= (function(x) {
alert(x);
var config = {
$config1: $( '#block'+x),
$config2: $( '#block-bottom'+x)
};
//more codes
})();
</script>
You probably want this:
<script>
var pages = function(x) {
alert(x);
var config = {
$config1: $( '#block'+x),
$config2: $( '#block-bottom'+x)
};
//more codes
};
//Then you can call pages like this
var a = pages("page1");
var b = pages("page2");
</script>
Basically, your problem is that your funcion declaration is wrong, you just made an invocation instead. Leave out the parenthesis and use your function as normal afterwards, here an snippet demonstrating the concept:
<html>
<head>
<script>
var pages= (function(x) {
alert(x);
var config = {
$config1: $( '#block'+x),
$config2: $( '#block-bottom'+x)
};
//more codes
});
</script>
</head>
<body>
<input type="button" onclick="pages(1)"> button 1</input>
<input type="button" onclick="pages(2)"> button 2</input>
</body>
</html>

Error : javascript Function Add to class dynamically

I am new to web development.
Today I learn about classes(function) in javascript. I got an error how to call dynamically added method.
My Code :
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
MyMethod("start", function () { return "hi"; });
var abc = this.start(); //gives error
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<input type="button" value="Click" onclick="MyFunction1()"/>
</div>
</form>
Here when I click the input button then not able to call the dynamically added function
How can i call the start() function that i added here.
Please Help me.
Thanks in Advance.
this in MyFunction1 referes to the global object in that case(for browsers it is window) , because you call MyFunction1 as function and you don't create an object by using new MyFunction1().
Another thing to be noted. You should not use eval when it is possible to do it without eval.
You can do the same thing using:
function MyMethod(name, fn) {
MyFunction1.prototype[name] = fn;
}
Using eval prevents you from using optimization tools or tools to validate your code. At least most of these tools don't take eval into account or even give a warning about that you are using it.
Try adding "new" before your onclick call to MyFunction1, creating an instance of it.
It reseolved I did
Hi , It resolved .Thanks for the gret help i did :
function fnOnload() {
MyMethod("start", function () { return "hi"; });
}
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
}
function MyFunction2()
{
var aa = new MyFunction1();
var answee = aa.start();
}
and in click of button i callled function MyFunction2()
without changing your code you can do as follow , but I say it would be helpful if you read about invocations types and about this variable.
function MyMethod(name, fn) {
MyFunction1.prototype[name]= fn;
return MyFunction1.prototype;
}
function MyFunction1() {
var myPrototype= MyMethod("start", function () { return "hi"; });
var returnValue = myPrototype.start();
console.log(returnValue);
}

Javascript not declaring variables

i'm new to JavaScript i have this script and i want to declare a variable on a if but on document.write , returns nothing what am i doing wrong ?
<head>
<script>
(function () {
setInterval(function () {
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
NetworkStatus.innerHTML = "Online";
NetworkStatus.className = "online";
var person="John Doe";
} else {
NetworkStatus.innerHTML = "Offline";
NetworkStatus.className = "offline";
var person="Santa Claus";
}
}, 100);
})();
</script>
</head>
<body>
<h1 id="status"></h1>
<script>
document.write(person + "<br>");
</script>
</body>
It's just all wrong, why use an IIFE and a timeout when all you have to do is add the script in the tag at the end of the DOM.
Also, you're setting the innerHTML of the element, and using document.write, which will overwrite the document ?
<head>
<title>I messed up</title>
</head>
<body>
<h1 id="status"></h1>
<script>
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
var person = "John Doe";
NetworkStatus.innerHTML = "Online " + person;
NetworkStatus.className = "online";
} else {
var person = "Santa Claus";
NetworkStatus.innerHTML = "Offline " + person;
NetworkStatus.className = "offline";
}
</script>
</body>
You are in IIFE. which creates its own scope
And that's where it stays
Do this :
window.person="Santa Claus";
Instead of what you're doing.
var sets the scope of the variable to the function it is declared within. You are trying to document.write it from outside that function, so it is out of scope and inaccessible.
Use window.person instead of var person.
The function executes after 100ms which means the person variable has no value when the page loads.

Categories

Resources