Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript runtime error: Unable to get property 'forEach' of undefined or null reference

I have an aspx Master page application where I have two dropdownlist controls in the asp:content section of the child aspx page. One of the controls is populated from SQL database. The other is populated based on the item selected from the first dropdown. I am trying to use this solution in my code, however I am getting an error:

JavaScript runtime error: Unable to get property 'forEach' of undefined or null reference

How can I get the city names to be displayed based on State selected?
My code block is:

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

    <script type="text/javascript">
        AL = new Array('Birmingham', 'Montgomery', 'Tuscaloosa');
        FL = new Array('Miami', 'FtLauderdale', 'Jacksonville');
        GA = new Array('Atlanta', 'Macon', 'Athens');

        populateSelect();

        $(function () {

            $('#ddlState').change(function () {
                populateSelect();
            });

        });

        function populateSelect() {
            category = $('#ddlState').val();
            $('#ddlCity').html('');

            eval(category).forEach(function (t) {
                $('#ddlCity').append('<option>' + t + '</option>');
            });
        }
    </script>  

<asp:DropDownList ID="ddlCity" runat="server" CssClass="stdFldWidth" onchange="setFDFlag()">
</asp:DropDownList>    

<asp:DropDownList ID="ddlState" runat="server" CssClass="stdFldWidth" DataSourceID="dsUSState"
    DataTextField="US_State" DataValueField="State_ID" AutoPostBack="true" > 
</asp:DropDownList>  

Update:

Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlType.SelectedIndexChanged
If ddlState.SelectedValue = "FL" Then
    DisplayRegulation(FL)
End If
like image 702
user3929962 Avatar asked Sep 09 '14 15:09

user3929962


2 Answers

The common issue with ASP.NET pages, specially if you use MasterPages.

The generated pages will have their elements IDs changed.

One solution for your problem is to give these elements a unique class and use it in the selector instead of their IDs:

<asp:DropDownList ID="ddlCity" runat="server" CssClass="stdFldWidth ddlCity" onchange="setFDFlag()">
</asp:DropDownList>    

<asp:DropDownList ID="ddlState" runat="server" CssClass="stdFldWidth ddlState" DataSourceID="dsUSState"
    DataTextField="US_State" DataValueField="State_ID" AutoPostBack="true" > 
</asp:DropDownList>

...

$(function () {
    var states = {
        AL: ['Birmingham', 'Montgomery', 'Tuscaloosa'],
        FL: ['Miami', 'FtLauderdale', 'Jacksonville'],
        GA: ['Atlanta', 'Macon', 'Athens']
    };

    function populateSelect() {
        $('.ddlCity').empty();

        var stateSelected = $('.ddlState').val();

        if (stateSelected) {
            states[stateSelected].forEach(function (sel) {
                $('<option>').val(sel).text(sel).appendTo($('.ddlCity'));
            });
        }
    }

    populateSelect();

    $('.ddlState').on('change', function() { 
        populateSelect();

        return true;
    });
});

Edited using @sebnukem recommendation to keep the data in an object, so you can get rid of the eval().

Updated by placing the whole code within the jQuery document ready event handler.

Updated by returning true in the jQuery onchange event handler for the DropDownList, to carry on with the PostBack.

Demo

like image 174
melancia Avatar answered Nov 08 '22 02:11

melancia


Never use eval. Store your data in an object instead:

var states = {
    'AL': ['Birmingham', 'Montgomery', 'Tuscaloosa'],
    'FL': ['Miami', 'FtLauderdale', 'Jacksonville'],
    'GA': ['Atlanta', 'Macon', 'Athens']
};

function populateSelect() {
    var category = $('#ddlState').val(); // selected state

    if (category && states[category]) {
        $('#ddlCity').html('');
        states[category].forEach(function (t) {
            $('#ddlCity').append('<option>' + t + '</option>');
        });
    } else {
        console.log('invalid state input: '+category); 
    }
}

$(function () {
    $('#ddlState').change(function () {
        populateSelect();
    });
    populateSelect();
});

I am assuming that the <asp:DropDownList> element does produce an HTML element with the specified ID.

like image 2
sebnukem Avatar answered Nov 08 '22 03:11

sebnukem