maxfax
maxfax

Reputation: 4305

Java Script: assign var in function and use var out that function

<script type="text/javascript">
var statustext="test";
$zack(function() {
  $zack.setOnStatus(changelable);
});
function changelable(status) {
  if (status=='A')
    statustext="OK";
  else if (status=='B')
    statustext="Ready";
  else if (status=='C')
    statustext="Go";
  document.getElementById('title').innerHTML = statustext; // OK, Ready or Go
}
</script>

document.getElementById('title').innerHTML shows OK, Ready or Go.

But when I use this script somewhere below the above script the statustext variable contains test text as pre assigned:

<script type="text/javascript">
document.getElementById('title2').innerHTML = statustext; // test
</script>

I want to use statustext with OK, Ready or Go text multiple times. How to do this?

Upvotes: 2

Views: 98

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

Your title2 code runs right away when the page is loaded, but your other code runs in response to an event (the status change event or whatever that calls changelable).

If you want to set title2 to the same thing you're setting title to, move this line:

document.getElementById('title2').innerHTML = statustext;

...into the changelable function, just after this line:

document.getElementById('title').innerHTML = statustext;

e.g.:

document.getElementById('title').innerHTML = statustext;
document.getElementById('title2').innerHTML = statustext;

or if you like:

document.getElementById('title').innerHTML = document.getElementById('title2').innerHTML = statustext;

Separately, your if/else if/else if sequence is really what the switch statement is for:

function changelable(status) {
  switch (status) {
    case 'A':
      statustext="OK";
      break;
    case 'B':
      statustext="Ready";
      break;
    case 'C':
      statustext="Go";
      break;
  }
  document.getElementById('title').innerHTML = statustext;
  document.getElementById('title2').innerHTML = statustext;
}

Or you could use a lookup table:

var statustext="test";
var statusLabels = {
    A: "OK",
    B: "Ready",
    C: "GO"
};
$zack(function() {
  $zack.setOnStatus(changelable);
});
function changelable(status) {
  statustext = statusLabels[status] || statustext;
  document.getElementById('title').innerHTML = statustext;
  document.getElementById('title2').innerHTML = statustext;
}

Upvotes: 4

Related Questions