how to affect the value of the global variable in javascript?

advertisements

I use the following script function for get the row id from the grid. It was working properly. I get the ID within the click function. But if I try to get the outside of the function it will display Empty. I need the click function value for selr outside? How to do this?

var selr='';
$(document).ready(function(){
               $("#datagrid").click(function(e) {
                 row = jQuery(e.target).closest('tr');
                 getId= row.attr("id");//for getting row number
                 selr = $("#datagrid").getCell(getId,'companyid');//getting Row ID
                 alert('alert in'+selr);
                 });
                  alert('alert out'+selr);
});


The thing is, the value of selr gets declared only when you initiate the click function. So check after clicking the jqGrid.

The script inside the $(document).ready(); will not work, and will show as empty because, after the document is ready, the selr wouldn't have set.

Instead of having a simple variable, assign selr as a global variable. Just replace selr with window.selr.

window.selr='';
$(document).ready(function(){
    $("#datagrid").click(function(e) {
     row = jQuery(e.target).closest('tr');
     getId= row.attr("id");//for getting row number
     window.selr = $("#datagrid").getCell(getId,'companyid');//getting Row ID
     alert('alert in'+window.selr);
     });
     alert('alert out'+window.selr);
});