views:

178

answers:

4

Hi,

I have a form in my content page for which I am doing some client side validations via Javascript. The Javascript behaves as expected if I place the JS code directly in the content page. But if I place the JS code in it's own file and try accessing that from the content/master page (through the script tag's src attribute), I get a run time error when the validation function in JS being called.

To be specific, I get the below error. Microsoft JScript runtime error: Objected expected/required at this line - document.getElementById('<%=txtemailId.ClientID %>').value

txtemailId is in the content page.

Javascript code is placed in validation.js and accessed via master page.

The reason I guess is that when .net is parsing the files, it is unable to substitute txtemailId.ClientID with the client side value that would be generated later on. So, how should one go about it? Thanks!

A: 

Standalone .js files are not run through the ASPX parser, so your expression is not being evaluated.

To solve the problem, you could set global variables (or function parameters, or something else) in the ASPX files with the IDs of the controls, then use them in the standalone .js file.

Alternatively, you could uses class names (which don't get mangled) instead of IDs. (This is very simple using jQuery)

SLaks
A: 

An approach like this is best suited for something you want to achieve:

validation.js

var Validation = {
     EmailId: null,

     Validate: function() {
          var email = document.getElementById(EmailId).value;
     }
}

page.aspx

Validation.EmailId = '<%=txtemailId.ClientID %>'; //initialize
Validation.Validate(); //whenever you want to validate
Jan Jongboom
A: 

You're right, the code <%=txtemailId.ClientID %> will only get replaced with the real client ID by ASP.Net if this code is in an ASP.Net file. So if you put this javascript in a separate .js file, ASP.Net will know nothing about it, and the code will not be parsed.

The easiest way to achieve this is to make the control IDs parameters of your functions. This way you can have the calling javascript code in your .aspx (or .ascx) file, along with the <%=txtemailId.ClientID %> code.

Graham Clark
A: 

The answer to this is quite simple.

Within your content page declare an in-line JScript variable, make sure this is above your tag.

<script> var emailClientId = <%=txtemailId.ClientID%>; </script>

Within your include.js file make use of the globally scoped emailClientId variable.

Obviously this is a bit clumsy because not all of the JScript code is contained within the include.js file, which makes it difficult to debug / diagnose as it is not clear specifically where the value is coming from. You should clearly comment / document this within your code to make maintenence of he codebase easier in the future.

DavidHalligan