Sam
Sam

Reputation: 948

Inserting Javascript into ASP.Net page

I have the code

<script type="text/javascript">
    function validateLength(objectSource, args) {
        var a = document.getElementById('<%=txtUserName.ClientID%>').value;
        args.IsValid = (a.length >= 5 && a.length <= 10);
    }
</script>

Which I have in my ASP.NET page.

This works fines. Will validate a textbox to make sure it is between a certain length.

However I am trying to tidy up my page's code. So decided to put this little function into a separate javascript file.

<script type="text/javascript" src="Scripts/MyJS.js">
</script>

Page loads fine and then when the validation comes around it fails. I am guessing it cannot access the textbox( txtUserName).

My question is: How can I get this to work?

I get the error message

0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined

when the javascript fires

Upvotes: 1

Views: 3930

Answers (2)

user3401335
user3401335

Reputation: 2405

When you include a javascript file, the part of code

<%=txtUserName.ClientID%>

isn't rendered.

You have to change the javascript function in two ways Fixing the name of the control

<script type="text/javascript">
    function validateLength(objectSource, args) {
        var a = document.getElementById('txtUserName').value;
        args.IsValid = (a.length >= 5 && a.length <= 10);
    }
</script>

or adding a parameter

<script type="text/javascript">
    function validateLength(objectSource, args, nameOfControl) {
        var a = document.getElementById(nameOfControl).value;
        args.IsValid = (a.length >= 5 && a.length <= 10);
    }
</script>

then you can call the function from your page and the parameter nameOfControl could be

<%=txtUserName.ClientID%>

for example

validateLength(objectSource, args, <%=txtUserName.ClientID%>)

Upvotes: 4

user887675
user887675

Reputation: 557

The <%=txtUserName.ClientID%> runs in context of your page. That will not work in a separate .js file. Separate .js files won't run any asp.net code. You could do something like:

JS file:

function validateLength(objectSource, args) {
    var a = document.getElementById(window.myValidatorId).value;
    args.IsValid = (a.length >= 5 && a.length <= 10);
}

ASP

<script type="text/javascript">
    window.myValidatorId = '<%=txtUserName.ClientID%>';
</script>

Or perhaps read the id from a hidden input field on the page.

Upvotes: 2

Related Questions