views:

405

answers:

2

Essentially I need to specify a JQuery variable in my webpage's body tag, and have a function in my head tag read it. This is the function in my head tag (simplified):

<script type="text/javascript">
$.noConflict();

jQuery(document).ready(function($) {

$('a.paymentAdd').click(function(){

alert ("rowCount 1 = " + rowCount);

  rowCount++;

 });
 });

</script>

And this in my body tag:

<script type="text/javascript">

      jQuery(document).ready(function($) {
       var rowCount = 3;
       alert ("rowCount 2 = " + rowCount);
      });

     </script>

(I have to specify the variable in my body tag because it is generated by PHP which is only available in that part of my template.)

When the page loads I get the alert "rowCount 2 = 3" (correct)

When I click a link with class "paymentAdd" I get the alert "rowCount 1 = undefined" (incorrect- expecting 3?)

+2  A: 

Declare the variable in the global scope outside of any document.ready functions:

var rowCount = 0;
jQuery(document).ready(function($) {
    rowCount = 3;
    alert ("rowCount 2 = " + rowCount);
});
Darin Dimitrov
A: 

You have declared the variable as local inside the function, so it doesn't exist outside it. A simple solution is to just declare it as global, and it will survive for later:

<script type="text/javascript">

  var rowCount = 3;

  jQuery(document).ready(function($) {
   alert ("rowCount 2 = " + rowCount);
  });

 </script>

However, declaring variables globally is always a potential risk of conflicts. If you have different scripts on the page each declaring their own set of global variables, they won't work together if they use the same variable names. If you have several variables like this that you need to access globally, you might want to create a single global object as a namespace and put them as properties:

var listData = {
   rowCount: 3,
   currentRow: null,
   sorting: 'Name'
}

Then you can access the properties:

alert("rowCount2 = " + listData.rowCount);

There is of course still a risk of conflicts between scripts, but it's far less with a single global object than with a bunch of global variables.

Guffa