user2380907
user2380907

Reputation: 15

Trouble calling JavaScript function on page load

I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.

I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">

    window.onload = refreshProjects(id);   <-- Problem

    $("#ddCustomers").change(function () {
        refreshProjects($(this).val());
    });
    function refreshProjects(id) {
        var projects = $("#ddProjects");
        $.get('@Url.Action("FilterProjects","TimeEntry")', { customerId: id },
        function (result) {
            // clear the dropdown
            projects.empty();

            //Add a deafult "null" value
            $("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1"); 

            // rebuild the dropdown
            $.each(result, function (i, e) {
                projects.append($('<option/>').text(e.Text).val(e.Value));
            });
        });
    }</script>
}

This is for MVC 4.5.

Upvotes: 1

Views: 4765

Answers (2)

sroes
sroes

Reputation: 15053

Try changing window.onload = refreshProjects(id); to:

window.onload = function() { refreshProjects($("#ddCustomers").val()); };

Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.

But since you seem to be using jQUery, you could do the following:

$(function() {
    refreshProjects($("#ddCustomers").val());
});

This will execute refreshProjects when the document is ready (which actually is before window load).

Upvotes: 2

Dustin Klein
Dustin Klein

Reputation: 319

You can also try to use the following:

$(document).ready(function () { 
    refreshProjects(id);
});

This should work aswell if you are using jQuery.

Upvotes: 0

Related Questions