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.

March 7, 2012

PHP String – Escape Single Quotes (for jQgrid Select Box)

Question by FastTrack

I have a string:

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'"

My problem is, the single quotes you can see in JR'S OFFICE and MFR's OFFICE are prematurely ending my string. I could switch my double quotes with single quotes and vice versa, but these are coming from user-entered values. If the user had entered a double quote, I would be in the same boat as I am now.

Any ideas on how to keep the integrity of this string while having single and double quotes throughout?

By the way, not sure if this matters for anything but – I’m putting my $departmentList string into a jQGrid to build the values for a select box.

Answer by xato

Use addslashes to replace " with " and ' with '.

Answer by Starx

If you are using the input for database purpose better use mysql_real_escape_string()

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'";
$data = mysql_real_escape_string($departmentList);
...

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