0

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...
}
1
  • 1
    Where do you call function2? Commented Jun 10, 2020 at 12:10

4 Answers 4

1

You mean like that:

function editBox() {
    var index = $(event.target).parent().attr("id");
    function2(index);
}

function function2(r) {
    //some code ( r is id now)
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will only work if function2 is called from inside editBox.
i know, but did not specify the way so this is one of the methods
0

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>

Comments

0

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().

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.