Javascript cannot find element id

I have my javascript function in a javascript file because this function use most of my page.

function setSecondaryItem() {
var select = document.getElementById("<%= SecondaryArea.ClientID %>");
var len = select.length;

I also put this in my page

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

I call this function when a dropdownlist change

<asp:DropDownList runat="server" ID="PrimaryArea" onchange="setSecondaryItem()" >
    <asp:ListItem Value="" Text="select..." Selected="True"></asp:ListItem>
    <asp:ListItem Value="A" Text="A.."></asp:ListItem>
    <asp:ListItem Value="B" Text="B.."></asp:ListItem>
    <asp:ListItem Value="D" Text="D.."></asp:ListItem>
    <asp:ListItem Value="E" Text="E.."></asp:ListItem>
    <asp:ListItem Value="F" Text="F.."></asp:ListItem>
<asp:DropDownList runat="server" ID="SecondaryArea" >
    <asp:ListItem Value="1" Text="1.."></asp:ListItem>
    <asp:ListItem Value="2" Text="2.."></asp:ListItem>
    <asp:ListItem Value="3" Text="3.."></asp:ListItem>
    <asp:ListItem Value="4" Text="4.."></asp:ListItem>
    <asp:ListItem Value="5" Text="5.."></asp:ListItem>

But I found that this will get an error : Uncaught TypeError: Cannot read property 'length' of null

Anyone can show me how to solve this problem?

Note: actually is two dropdownlist in page. change dropdownlist1 will call the function to change dropdownlist2.



This <%= SecondaryArea.ClientID %> that you are using is known as Code Block. You can also refer to this question on stackoverflow for more details.

Code Blocks can't be placed in external JavaScript files because they need to be rendered as C# code.

As your JavaScript function setSecondaryItem is used in many pages and of course it's not good to repeat it, you need to define your function in an external JavaScript file and call it (in any page you need) with your Code Block as an argument.

Your external JavaScript file:

function setSecondaryItem(secondaryAreaId) {
    var select = document.getElementById(secondaryAreaId);
    var len = select.length;

And in your .aspx file:

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

<script type="text/javascript">
    setSecondaryItem("<%= SecondaryArea.ClientID %>");

From select.length you should get item length, if still not getting try following line of code, may be it will help you.



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.