1

I have a working asp.net page, everything was working properly till I moved the Script content to a separate js file. Example I have a script function:

function selectValue(){
var oldvalue = document.getElectByID(“<%=ddlAccountType.ClientID%>”).value
..
..
..}

Visual Studio is throwing an error saying JavaScript runtime error: Unable to get property ‘value’ of undefined or null reference. And this is just one example. Please help!

Neel
  • 1,771
  • 2
  • 18
  • 30

3 Answers3

2

The problem is that you moved the script out of your .aspx-file or whatever you used.

ASP.Net only compiles .aspx, .cshtml, .vbhtml, etc. -files, which means that your server-side code isnt compiled and will be parsed by the browser as javascript.

This will be parsed by the browser:

document.getElectById("<%=ddlAccountType.ClientID%>") // returns undefined

var oldvalue = undefined.value // JavaScript runtime error: Unable to get property ‘value’ of undefined or null reference
DavidVollmers
  • 620
  • 4
  • 15
2

The problem here is that your JS file doesn't recognize this tag

<%=ddlAccountType.ClientID%>

it only works on the .aspx file, but there is a solution/workaround:

in your .aspx use this snippet:

<script type="text/javascript" language="javascript">
    var ddlAccountType = document.getElectByID(“<%=ddlAccountType.ClientID%>”);
</script>

and in your JS file:

function selectValue(){
var oldvalue = ddlAccountType.value
..
..
..}
Enrique Zavaleta
  • 2,058
  • 3
  • 22
  • 28
1

This is happening because JavaScript files are read by the browser, never by the ASP.NET engine, even though they're resident on the server. The ASP.NET engine therefore never processes your (“<%=ddlAccountType.ClientID%>”) tags.

Anything you want processed by the ASP.NET engine MUST appear on your page or in a user control. You can try parameterizing your external-file methods and passing in the values, in this fashion:

function selectValue(id){
  var oldvalue = document.getElectByID(id).value;
  ..
  ..
..}

In your page:

selectValue("<%=ddlAccountType.ClientID%>")

By the way, you aren't really using "curly quotes" for your markup, are you? That will probably cause you problems.

Ann L.
  • 12,802
  • 5
  • 30
  • 60
  • yes, i am using double quotes is it something like big "no no" for JS? – Neel Jul 06 '15 at 13:42
  • so this will also cause problem when i am trying to set a value of a server side control! – Neel Jul 06 '15 at 13:44
  • No, double quotes like this `"` are fine. It's just curly double quotes (like you get when you paste from Word) that might be a problem. They look like this: `“”` – Ann L. Jul 06 '15 at 13:55
  • A server side control (like a user control) shouldn't be a problem. The `.ascx` file is read and processed by the ASP.NET engine. – Ann L. Jul 06 '15 at 13:56