Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
2.40/5 (2 votes)
See more:
Hi Experts,

Could you please see my below code and kindly tell me why I am getting undefined from gup function.

C#
function BtnSelect_Click_Complete(values) {

            var ofiledname;
            //var oParticipantListID;

            //oParticipantListID = participantListID();

            //alert('aaa');
            ofieldname = gup('fieldname');           
            if (ofieldname != null) {
                //alert(ofieldname + " : " + values[0] + " : " + values[1]);
                window.opener.SetLookup(opener.document, ofieldname, values[0], values[1]);
                window.opener.PopulateParticipant(values[0], ofieldname);
            }
            self.close();
        }


C#
function gup( name )
{
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;    
    var results = regex.exec( tmpURL );
    if( results == null )
        return "";
  else
    return results[1];
}


Please help me, I have production issue.
Thanks in advance.

Shafik
Posted
Updated 15-Jul-15 7:48am
v3
Comments
SohaibX 15-Jul-15 14:22pm    
"JavaScript is getting undefined" usually means that your javascript library is not correctly loaded.
Sergey Alexandrovich Kryukov 15-Jul-15 16:08pm    
No, the inquirer did not mean that, he meant return from this function. I answered the question, please see.
—SA

1 solution

According to the documentation, exec returns either array or null, but not undefined. So, if (results == null) return ""; could not cause a problem. Lets look at "else" part. If results has less then two members, you could have undefined return from your function. If you could use JavaScript debugger, you would easily find it out.

So, as to the first point, the condition under "if", I would prefer to be on the safe side, so I would write
JavaScript
if (results) { // not comparing with null, to be of safe side
   if (results.length > 1) // we don't know know if we have an element at [1]
      return results[1];
   else
      return ""; // no second element
} else
   return ""; // wouldn't null be better?

Instead of returning "" in two cases, you could return something different, to distinguish the case when the array is not long enough to have an element at [1], and the case where there is no a match at all. That's why I suggested to return null in this case, "" in another one. Or something like that. Also, you could think of checking up name for null and then empty string before using Regex, to pass the same values to return.

—SA
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900