Lau Lau - 1 month ago 7
Javascript Question

Access local variable in another function without using global

I need to match the value of multiple

textareas
to the properties of an object. It should only be a match if :


  1. the value of the
    textarea
    being used is equal to the person's name contained in the object and

  2. if the index of the textarea is equal to the person's ID. (Cf
    boolean in my fiddle : https://jsfiddle.net/Lau1989/hxcpstty/1/)



To do this I need to access the object
test = {}
from this function :

function make_test(name, job, ID) {
var test = {}; //local variable to be used in 'function suggest(index)'
test.name = name;
test.job = job;
test.ID = ID;
return test;
}
new make_test("Paul", "manager", 1);
new make_test("John", "employee", 2);
new make_test("Jan", "employee", 2);


Inside this one :

function suggest(index) {
if (test.ID === index && test.name == thisInput.value) {
thisOutput.innerHTML = "Has job : " + test.job; //should access 'test' properties : test.name, test.job, test.ID
}
}


Problem is that declaring
test = {};
as a global variable will only allow
function suggest(index)
to find 'Jan' because it is the last one I declared. But if I declare
var test = {};
as a local variable it won't work at all because
function suggest(index)
can't access
var test = {};
from outside.

This is where I'm stuck. My goal is to access
var test = {};
within
suggest()
to get every person's job depending on their
name
and
ID
.

Thanks for your help

Answer

Given that your employee IDs don't seem to be unique, I'd suggest you store all the people in an array, then in your suggest() function you can search through the array to check for a match (click Run code snippet to try it out):

function make_test(name, job, ID) {
  var test = {};
  test.name = name;
  test.job = job;
  test.ID = ID;
  return test;
}

var people = [];

people.push(make_test("Paul", "manager", 1));
people.push(make_test("John", "employee", 2));
people.push(make_test("Jan", "employee", 2));

function suggest(index) {
  var thisInput = document.getElementById("textarea" + index);
  var thisOutput = document.getElementById("output" + index);

  thisOutput.innerHTML = "Has job:";

  for (var i = 0; i < people.length; i++) {
    if (people[i].ID === index && people[i].name == thisInput.value) {
      thisOutput.innerHTML = "Has job: " + people[i].job; //should access 'test' properties : test.name, test.job, test.ID
      break;
    }
  }
}
<table>
  <tr>
    <td><textarea onkeyup="suggest(1)" name="response" id="textarea1" cols="30" rows="5"></textarea></td>
    <td><div id="output1">Has job :</div></td>
  </tr>
  <tr>
    <td><textarea onkeyup="suggest(2)" name="response" id="textarea2" cols="30" rows="5"></textarea></td>
    <td><div id="output2">Has job :</div></td>
  </tr>
</table>

Note that it doesn't make sense to call your make_test() function with new, because you manually create a new object inside the function.