H. Eberhardt H. Eberhardt - 1 month ago 9
jQuery Question

jQuery HTML only runs when called manually

I have a small problem, that I could not find the solution.

I have the code below and, when my page loads, it doesn't work, but if I open "Console" and type Preenche(); it fills my page.

function Preenche() {
$("#Apple").html(apple);
$("#Windows").html(windows);
}

Preenche();


I want to understand What's happening...

Thanks!




Update:

I tried to use:

$().ready(Preenche());

$(document).ready(function () {
$("#dataUltimaChave").html(dataUltimaChave);
$("#qntChaves").html(qntChaves);
});

$(function () {
Preenche();
})


in the end and start of document but nothing worked. I'm using ASP.NET MVC5, don't if this matters..

I'm using jQuery: jquery-1.10.2.min.js

Answer

It seems your script is declared before the DOM elements with id 'apple' and 'windows' are even loaded. You need to wrap the function either window.onload or $(document).ready()

<script>
window.onload = function()  // or $(document).ready(function()
{
    function Preenche() {
        $("#Apple").html("hello");
        $("#Windows").html("world");
    }

    Preenche();
}
</script>

Example : http://jsfiddle.net/xBB5x/12555/