September 4, 2012

how to assign the value for global variable in javascript?

Question by User

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);
});

Answer by Praveen Kumar

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);
});

Answer by Starx

You are already assigning the variable as global.

The problem is the variable is initiated inside a function which is triggered on click of $("#datagrid") and the alert('alert out'+selr); executes upon DOM Ready Event, most probably before the click event triggers.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!