Reputation: 3
I want to set the var index if the button is clicked. But I also want to use var index in function2. Is there a way to do this without using a global (f.e. by using return)?
HTML:
<button id="edit" onclick="editBox()">Bearbeiten</button>
JS:
function editBox() {
var index = $(event.target).parent().attr("id");
}
function function2() {
//some code...
}
Upvotes: 0
Views: 73
Reputation: 137
Short answer: index
need to exist in a large scope than the editBox scope.
You don't want a global variable, so you can do it creating a "closure". In Javascript, you can do it using a IFFE (Immediately Invoked Function Expression). In this way, a number of functions and other piece of code share the same scope, but it still "local", not global.
(function(){
var index;
$('#edit').on('click', function editBox(event) {
index = $(event.target).parent().attr("id");
});
function function2() {
// some code
console.log(index);
}
// Other code that can call function2 and use index variable...
})();
<button id="edit">Bearbeiten</button>
Upvotes: 0
Reputation: 136
You should first define a variable out of the scope of functions to then call/assign it.
Here you have a working snippet.
let value;
function func1(id) {
value = id;
console.log('clicked', id);
}
function func2() {
alert(value);
}
<button id="btn" onclick="func1(this.id)">
Click me and get the id
</button>
<button id="btn2" onclick="func2()">
Call second function
</button>
Upvotes: 0
Reputation: 2548
If a variable is declared inside a function, its scope is limited to that function and there is no way to access its value from outside the function.
From w3schools:
Local variables have Function scope: They can only be accessed from within the function.
To access the same variable inside the second function as well, it must be declared using the var
keyword outside of both functions. For example:
var index;
function editBox() {
index = $(event.target).parent().attr("id");
}
function function2() {
console.log(index);
}
The only other possibility is passing the variable index
to function2()
as a parameter, but this will only work if function2()
is called from inside editBox()
.
Upvotes: 0
Reputation: 8162
You mean like that:
function editBox() {
var index = $(event.target).parent().attr("id");
function2(index);
}
function function2(r) {
//some code ( r is id now)
}
Upvotes: 1