user3881476
user3881476

Reputation: 3

javascript variable assignment

Utterly stumped as to why the below javascript doesnt assign the variables as expected

Maybe I am missing something very simple due to staring at it for hours on end !!

Any help appreciated.

Cheers

var $name;
var $district;
var $distance;
var myArray = [];

jQuery('.getrowdata').on('click', function(){   
  var $row = jQuery(this).closest('tr');
  var $columns = $row.find('td');
  var value;
  jQuery.each($columns, function(i, item){
    value = item.innerHTML;
    if(i < 3){
      myArray.push(value); // adds first 3 elements to the array
    }       
  }
);

$name = myArray[0]; // trying to set value of these variables to value of array element
$district = myArray[1];
$distance = myArray[2];

alert(myArray.join(",  ")); // this works - displays data as expected !!

});

document.write($name);   // these don't work - print out as undefined ?
document.write($district); 
document.write($distance); 

Upvotes: -1

Views: 72

Answers (1)

royse41
royse41

Reputation: 2368

The variables are undefined as they only have values after the "click" event handler is called.

Try moving your document.write statements into the "click" handler:

jQuery('.getrowdata').on('click', function() {

   ...

   document.write($name);
   document.write($district); 
   document.write($distance);
});

Upvotes: 2

Related Questions