It would appear there is some sort of an auto-casting problem in JavaScript. I have an external JavaScript file included into a page which defines a set of arrays, a line from the file looks like this:
var resortPAArray = new Array('("1 Bed","1 Bedroom","2","3")','("2 Bed","2 Bedroom","3","5")','("Penthouse","Penthouse","4","10")');
The two numbers in each inner array represent the minimum and maximum people allowed to stay in that room type, for instance a 2 Bed bedroom can sleep a minimum of three and a maximum of five. There is a line in the JavaScript file for each building and they are used to auto-populate a booking form (to save posting back to the server on every change). The scripts were executing without error, until we added a room type which allowed ten (10) or more people in it.
When you select the building, it uses the inner arrays to populate a dropdown box with the room types (1 Bedroom, 2 Bedroom, ..). Once you select the room type, it then populates the next dropdown with the corresponding min/max people for that room type. Out of interest, the min/max values are assigned as follows where tmpArray
represents an inner array:
minpax=tmpArray[2];
maxpax=tmpArray[3];
From here, those values are used in a for
loop as follows:
for (var i=minpax; i<=maxpax; i++) {
// code here
}
Remember, at this point the script is executing without any problems. When the values are assigned to the minpax
and maxpax
variables, they are technically strings – since they are defined in the inner arrays with quotes around them. Conveniently, JavaScript auto-casts values for you – as such the strings are cast to a numeric internally and the mathematic comparison is done.
Unfortunately, when a string value of 10 was assigned to maxpax
, the for
loop never executed and the as such, you couldn’t select how many people you wanted in that room. Initially, it made no sense at all. The JavaScript file for this building was structurally sound, no missing quotes, brackets or commas. All the values were in place, no strange characters at all – it was, for all intensive purposes, just like all the others.
The solution was quite simple, explicitly cast the values for minpax/maxpax when they are initially assigned or during the for
loop.
for (var i=parseInt(minpax); i<=parseInt(maxpax); i++) {
// code here
}
Mr. Lattimore,
This solved a problem that I’ve been chasing for the better part of a week.
Thank you.
Regards,
John McPherson
Software Developer
“Sufficiently advanced technology is indistinguishable from magic.”
Arthur C. Clark, inventor of the telecommunications satellite