Passing variables betwen functions in JQuery [duplicate] - javascript

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.

Related

How do I pass the values of a series of variables into a jQuery on() event as they are when the event is added? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 4 months ago.
This is the full code of the function (the event_option function itself works fine, but it just isn't recieving the proper parameters):
function fire_event(event, scopes) {
if (scopes[scopes.length-1] == data_player) {
opts = ""
i = 0;
data_events[ event ].options.forEach(option => {
opts += `<br><button id="event-${event}-option-${i}">${localisation[data_events[ event ].options[i].name]}</button>`
i += 1;
});
eventhtml = `<div id="event-${event}" class="event">
<h2>${localisation[ data_events[ event ].title ]}</h2>
<p>${localisation[ data_events[ event ].desc ]}</p>
${opts}
</div>`
$("#events").html($("#events").html()+eventhtml);
i = 0;
data_events[ event ].options.forEach(option => {
$(`#event-${event}-option-${i}`).click(function() { event_option(event, i, scopes) });
i += 1;
});
$(`#event-${event}`).on('mousedown', handle_mousedown);
}
}
This function, specifically the lines
data_events[ event ].options.forEach(option => {
$(`#event-${event}-option-${i}`).click(function() { event_option(event, i, scopes) });
i += 1;
});
is meant to make it so that clicking on the button will fire event_option(event, i, scopes) where the three values are meant to be as they were when the click function was added. However, clicking the button makes it use the values of the variables as they are when the click occurs.
(I also apologise for using the word "event" for one of the parts of my code despite not meaning actual code events.)

How to get "this" object in to a callback function? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
How do I get this into a callback?
Started out with this, worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
});
this.reload();
},
});
Then to only call reload if the request worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
this.reload();
});
},
});
Of course "this" is no longer references the object I want to access.
Or how would I gain access the parent object?
You may just bind your this inside the callback.
Note: Beware of any side-effects. Apparently you don't seem to need the new this inside the callback.
Try:
$('#grid').w2grid({
name: 'grid',
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], (function(data) {
this.reload();
}).bind(this));
}
});
When arrow-functions are available, I'd suggest to use them rather than binding this.
You can do it like this:
let parent = this;
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
parent.reload();
});

Javascript "Cannot read property length from undefined" bug [duplicate]

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

How to pass value of inner function to outer function in javascript? [duplicate]

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.

anonymous function calls with scoping issues [duplicate]

This question already has answers here:
passing index from for loop to ajax callback function (JavaScript)
(3 answers)
Closed 8 years ago.
I'm sure this has been asked before, but I don't know what to search for.
So I want function to be called with a string that corresponds with the item clicked, but I want to simply add any new items to an array of strings.
var menuList = ["overview", "help", "search"];
var functionCalls = [
function() { toggleMenu(menuList[0]); },
function() { toggleMenu(menuList[1]); },
function() { toggleMenu(menuList[2]); },
];
which is used like this in a loop: $("something").click(functionCalls[i])
This is what I want to do (but obviously it doesn't work):
for (var i in menuList) {
// This does not work because the closure references 'i'
// which, at the end, is always the index of the last element
$("something").click(function() {
toggleMenu(menuList[i]);
});
// this works, but I have to define each closure
$("something").click(functionCalls[i]);
}
How can I create an anonymous function that accepts a value based on a variable - but doesn't retain the reference to the variable?
You could use an IIFE like this:
for (var i=0; i<menuList.length; i++) {
!function( index ) {
$("something").click(function() {
toggleMenu( menuList[index] );
});
}( i );
}
By calling the anonymous function, you create a local copy of the current value for i with the name index. Hence, all handlers receive their respective version of i.

Categories

Resources