Thomas Nielsen
Thomas Nielsen

Reputation: 613

Onclick needs to be happening on page load

I have this piece of code with a little Javascript inside it, when I press the button it calculates a price and shows the result. But I want this price to be calculated at soon as the page loads. I figured this must be what the onload is for, but that didn't help?

<div>
    <p>200</p>
    <div id="label1"></div>
    <input type="button" value="calculate" onclick="calculate('calcObject1','label1',200)" />
</div>

Upvotes: 0

Views: 152

Answers (5)

kostisalex
kostisalex

Reputation: 51

You can use the onload property of the body tag. Take a look in this fiddle:

http://jsfiddle.net/kostisalex/wHLn3/20/

<body onload="calculate('fromBody1','fromBody2',200)">
    <div>
        <input type="button" value="calculate" onclick="calculate('calcObject1','label1',200)" />
    </div>

Upvotes: 0

pascalvgemert
pascalvgemert

Reputation: 1247

You can also use document ready, like:

<script type="text/javascript">
$(document).ready(function() {
    calculate(..);
});
</script>

Upvotes: 0

Andrew
Andrew

Reputation: 20111

Since you have tagged jQuery, you can use this to trigger a click event.

Give your button an id, such as btn1, then call:

$('#btn1').click();

or if you dont like id's, you can do this, but it will click all buttons on the page:

$('input[type="button"]').click();

http://api.jquery.com/click/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

There is no need to raise the click event here, as you can just call the calculate event when the page has loaded:

$(function() {
    calculate('calcObject1', 'label1', 200);
});

Or using native JS:

window.onload = function() {
    calculate('calcObject1', 'label1', 200);
}

Upvotes: 2

Nick
Nick

Reputation: 2646

You have to run the code in onload event of the body element: <body onload="calculate(...)">

Upvotes: 0

Related Questions