Meta Mussel
Meta Mussel

Reputation: 590

JavaScript is converting a String to a String and causing an error

I have a Delphi app with some embedded JS. I have a Function

function PlaceRecords(Lat, Lang, RecordNum, Dist, IconNo){
    var latlng = new google.maps.LatLng(Lat,Lang);
    PutMarker(IconNo, Lat, Lang, "Record " + RecordNum + " at "  +Dist + " miles");
}

As long as does not have with a letter in the RecordNum. I pass in all the arguments as strings but for some reason, JS wants to convert RecordNum to an number. How can I suppress this. Using IE 8.

Upvotes: 0

Views: 72

Answers (1)

Lambart
Lambart

Reputation: 2096

Well (based on your reply to my comment), if you could see the Javascript your code is generating, it would look something like this:

PlaceRecords(45.5262404, -122.6810841, A51210876, 123, 456);

Now do you see the problem?

You may be starting out with a bunch of strings, but you're not enclosing them as quotes, so Javascript doesn't consider them strings. 51210876 works because it's a number--even if you put it in quotes, it would be handled almost the same by Javascript. But as with most languages (I haven't written Pascal in almost 30 years but I'm certain it's the same), A51210876 is going to be considered an identifier name rather than a value, since it begins with an alpha character.

Assuming you can freely place double-quotes inside single quotes, I suggest you try something like this:

procedure TfrmMain.PlaceRecords(Lat,Lon,RecordNum, Dist:string; IconNo:integer);
begin
    HTMLWindow2.execScript(Format(
        'PlaceRecords(%s, %s, "%s", "%s", "%s")',
        [Lat,Lon, RecordNum, Dist, IntToStr(IconNo)]),
        'JavaScript'
    );
end;

I know that lats and longs are numbers so I didn't place them in quotes. I don't know what sort of data the last two arguments contain, so I put them in quotes too. I imagine you could probably put them all in quotes, because any Javascript down the line that expects a number "should" be ensuring the value is actually treated as a number.

Note that in Javascript, strings can be enclosed by single OR double-quotes, which is pretty convenient at times like this.

Upvotes: 1

Related Questions