I’m using the following function but it does work, can someone please point out what is wrong.
The vb variable is generated from a database query.
window.onload function PostCodeChecker() {
if (<%= sPostalCode %> !== 'SW') {
alert("This is not an SW Postal Code");
}
}
What’s really happening here is that your server-side code is swapping in the value where you’ve put
<%= sPostalCode %>, and sending the result to the browser. So if thesPostalCodewere (say) “NW10”, you’d getSo you’ll need quotes around it (and you’ll need to add the missing
=), like this:…so that what goes to the browser is:
That assumes that the string won’t have any
'characters in it, or other characters that would result (when the server-side processing is done and the result sent to the browser) in an invalid JavaScript string literal.Of course, you could just do this:
…since it’s a server-side variable, you can do the test server-side.
Side note: This form of expression:
…has issues on various browsers, most notably IE. It’s called a named function expression because it’s a function expression where the function has a name (
name, in this case). On IE it results in two completely separate functions being created, which can be ever so confusing. More: Double-take