-1

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); 
1
  • 2
    Your variables are undefined since they have some values assigned only after the user clicks . getrowdata . Commented Aug 11, 2014 at 11:53

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks guys, I have moved the variable assignment into the click handler - but the variables dont seemto be persistent?
persistent with what? they will retain their values - but they are only given values AFTER the user has clicked.
@user3881476 no worries. glad you got it sorted!

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.