Link to home
Start Free TrialLog in
Avatar of gerrie-govaerts
gerrie-govaertsFlag for Belgium

asked on

First click on a select box in MVC

When using multiple items, clicking the first time on a select box within MVC does not fire off the change event in jQuery (using the onChange event of the select item works fine).

Only the second time I click on a value, I get a response.

What could this be?

                    <select id="MaterialsList" class="StockListBox" size="2">
                    <% foreach (var material in Model.Materials)
                       { %>
                         <option value="<%: material.Value %>"><%: material.Text %></option>
                    <% } %>                
                    </select>   

Open in new window

           

My jQuery code:

    $(document).ready(function () {

        $("#MaterialsList").change(MaterialsListChanged);

        //////////////////////////////////////
        function MaterialsListChanged() {
            alert('ok');
            $("#ModelsList > option").remove();
            var materialId = $("#MaterialsList option:selected").val();
            $.post("/Stock/LoadBrands/" + materialId, null, function (data) {
                data = $.map(data, function (item, a) {
                    return "<option value=" + item.Value + ">" + item.Text + "</option>";
                });
                $("#BrandsList").html(data.join(""));
            });
        }

Open in new window


Thx in advance

Gerrie
Avatar of nmarun
nmarun
Flag of India image

Here's a snippet that worked on machine.

Arun

    <select id="MaterialsList" class="StockListBox" size="2" onchange="MaterialsListChanged();">
        <% foreach (var material in Model)
           { %>
        <option value="<%= material.Value %>">
            <%= material.Text %></option>
        <% } %>
    </select>
    
    <script language="javascript" type="text/javascript">
        function MaterialsListChanged() 
        {
            alert('ok');
        }
    </script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of nmarun
nmarun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gerrie-govaerts

ASKER

Hello

Your first solution isn't working because I'm dealing with jQuery functions and the onChange event of the listbox can't reach that one apparently.

The second solution however is correct, capturing the Click event instead of the Change event has helped me!