javascriptc#asp.netasp.net-4.5

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


Solution

  • 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%>)