This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I have one problem with javascript global variable,namely,i have global variable niz_opcija2,and i initialize it in one function,but in other function,it says it is undefined..
this is my javascript:
var niz_opcija2=[];
window.onload=function(){
ucitaj2();
ucitajKategorije();
}
function ucitaj2(){
$.get("/manager/categoriesArticle",function(data){
niz_opcija2.push(data);
console.log(data);
var select=document.getElementById("select3");
for(var i=0;i<niz_opcija2[0].length;i++){
var option=document.createElement("option");
option.value=niz_opcija2[0][i].categoryCode;
option.innerHTML=niz_opcija2[0][i].name;
option.id=niz_opcija2[0][i].name;
select.appendChild(option);
}
});
}
function ucitajKategorije(){
for(var i=0;i<niz_opcija2[0].length;i++){
var select=document.getElementById("selectKateg");
var option=document.createElement("option");
option.value=niz_opcija2[0][i].name;
option.innerHTML=niz_opcija2[0][i].name;
option.id=select.length;
select.appendChild(option);
}
}
(in this code i am trying to get data as json using $.get,and add it to select lists select3 and selectKateg,and ucitaj2() function is getting the data,but ucitajKategorije isn't,but I think it should work the same?)Does anyone know what can be the problem?Thanks in advance!
The issue is happening because your intialization of niz_opcija2 happens inside an asynchronous function call.
ucitaj2 returns immediately before $.get("/manager/categoriesArticle" has returned with data form the server.
Change to calling it in the get succes function:
var niz_opcija2=[];
window.onload=function(){
ucitaj2();
}
function ucitaj2(){
$.get("/manager/categoriesArticle",function(data){
niz_opcija2.push(data);
console.log(data);
var select=document.getElementById("select3");
for(var i=0;i<niz_opcija2[0].length;i++){
var option=document.createElement("option");
option.value=niz_opcija2[0][i].categoryCode;
option.innerHTML=niz_opcija2[0][i].name;
option.id=niz_opcija2[0][i].name;
select.appendChild(option);
}
//Call it here
ucitajKategorije();
});
}
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 10 months ago.
How can i pass var selekcija to another function? I need to pass var selekcija to another file (load-epizode.php), but my var is i another function.
var selekcija
$(document).ready(function() {
$('#sezona').change(function() {
selekcija = 1;
selekcija = $('#sezona').val();
console.log(selekcija);
});
$('#epizds').load("/filmovi2/config/load-epizode.php", {
NewSelekcija: selekcija
});
});
Do you want to load content on every 'change' event ?
Move the load inside the change event's function
function onSelekcijaChange() {
const selekcija = $('#sezona').val();
console.log(selekcija);
$('#epizds').load("/filmovi2/config/load-epizode.php", {
NewSelekcija: selekcija
});
}
$(document).ready(function() {
onSelekcijaChange();
$('#sezona').change(onSelekcijaChange);
});
Not the best and optimal JS code but I didn't want to change a lot
of your code.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I'm new to this so i guess i'm missing something simple. The foor loop works fine but inside it i get an undefined variable
var categories_info = ["historia","excelencia","arte","social","instalaciones","padres","familia"];
for ( var i = 0; i < categories_info.length; i++) {
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});
};
You need to create a closure like
var categories_info = ["historia", "excelencia", "arte", "social", "instalaciones", "padres", "familia"];
for (var i = 0; i < categories_info.length; i++) {
(function(i) {
$("#showMe-" + categories_info[i]).click(function() {
$(".info." + categories_info[i]).addClass("info-show");
console.log(".info." + categories_info[i]);
});
})(i);
};
This method is known as an IIFE
Basically, what was happening is the variable i was unavailable to the callback when the actual click happened.
However, by passing i in a self-executing anonymous function, you have created a closure which will preserve i and is accessible to the click handler.
Use a closure. Change:
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});
To:
(function( i ) {
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]);
});
})( i );
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I want to pass value of inner function to outer function. I want to change value of a=2 when treeImage is clicked. Here is my code, what I am doing wrong?
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
var a;
var treeViewData = window["<%=TreeView2.ClientID%>" + "_Data"];
var treeView1 = $('#<%= TreeView2.ClientID %>');
var treeNodes = treeView1.find("div[id$=Nodes]");
var treeImages = treeView1.find("img").not("img[alt=\'\']");
treeImages.click(function () {//if image is clicked a should be 2
a = 2;
});
if (treeViewData.selectedNodeID.value != ""&&a!=2)
{
$find("dde").hide();
}
else
{
$find("dde").show();
}
}
</script>
Put var a outside EndRequestHandler().
What you're doing in your code is a closure, but it's a pointless closure at that. The function for treeImages.click is "closing around" the a variable, but given your code it doesn't really act any different than if var a were inside the treeImages.click function.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I'm trying to use chrome.storage.local in my extension, and it doesn't seem to work. I used localStorage but realized that I can't use it in content scripts over multiple pages.
So, this is what I've come up with:
function save()
{
var channels = $("#channels").val();
var keywords = $("#keywords").val();
chrome.storage.local.set({'channels': channels});
chrome.storage.local.set({'keywords': keywords});
}
I do believe I'm doing the save() right, but the problem comes up in load():
function load()
{
var channels = "";
chrome.storage.local.get('channels', function(result){
channels = result;
alert(result);
});
var keywords = "";
chrome.storage.local.get('keywords', function(result){
keywords = result;
alert(result);
});
$("#channels").val(channels);
$("#keywords").val(keywords);
}
When the alerts trigger, it prints out [object Object]. Why is that? What am I doing wrong? I looked at the documentation/examples, but I can't seem to pinpoint the problem.
This code works for me:
function load() {
var channels = "";
var keywords = "";
chrome.storage.local.get('channels', function (result) {
channels = result.channels;
alert(result.channels);
$("#channels").val(channels);
});
}
Chrome.storage.local.get() returns an object with items in their key-value mappings, so you have to use the index of the key in your search pattern.
IMP:
Thanks to Rob for identifying: Chrome.storage.local.get() is asynchronous, you should modify your code to ensure they work after callback() is successful.
Let me know if you need more information.
debug or use
alert(JSON.stringify(result));
for more details as to what you are getting back
The "result" value you are using is an object that contains the storage value, to get the value you have to use result.keywords, which will get the value of the keywords. EX:
function load(){
chrome.storage.local.get('keywords', function(result){
var keywords = result.keywords;
alert(keywords);
});
chrome.storage.local.get('channels', function(result){
var channels = result.channels;
alert(channels);
});
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript closure inside loops - simple practical example
I am using webservice to get the data in the form of JSON by using javascript and want to store that data in Sqlite Database. here i used for loop to store data one by one in Database by executeSql Query. But problem is function inside the for loop getting "i" value out of scope means showing undefined. I am trying to solve this problem by last 5 days. Any suggestion ?
Thanks
function GetGeoValues() {
$.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something", function (Jdata) {
var geoid = new Array();
var geoname = new Array();
var i;
for (i = 0; i < Jdata.vact_geography.length; i++) {
geoid.push(Jdata.vact_geography[i].geo_id);
geoname.push(Jdata.vact_geography[i].geo_name);
db.transaction(function (transaction) {
alert(geoid[i]); // here i showing undefined
transaction.executeSql('INSERT INTO vact_geography VALUES(' + parseInt(geoid[i]) + ',"' + geoname[i] + '")');
});
}
});
}
I'm not sure, but this can happen, if function(transaction) executed in asynchronous mode. In this case variable i after for loop is finished must be equals to Jdata.vact_geography.length, and, as result geoid[i] equals to undefined. To workarround this try next:
function GetGeoValues() {
$.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something",
function(Jdata) {
var geoid=new Array();
var geoname=new Array();
for(var i=0;i<Jdata.vact_geography.length;i++) {
geoid.push(Jdata.vact_geography[i].geo_id);
geoname.push(Jdata.vact_geography[i].geo_name);
}
db.transaction(function(transaction) {
for(var i=0;i<geoid.length;i++) {
alert(geoid[i]); // here i showing undefined
transaction.executeSql('INSERT INTO vact_geography VALUES('+parseInt(geoid[i])+',"'+geoname[i]+'")');
// All INSERT's executed in one transaction
}
});
}
);
}
Here inner function and outer function concept is considered. So the outer function have the var i. But in inner function i is not defined. Thats y its throwing error as "undefined"