-3

My .ready() method does not call the function that it supposed to. The function alone is working fine, but when I try to execute it as the first thing after page is loaded, it does nothing. I went through existing topic but could not find the way of fixing it.

I should add that I want my function to be executed after page is loaded as well as after clicking a button(that part works at the moment)

My code:

<script>
$(document).ready(function() {
    calculation();
});

function calculation() {
    variable = new XMLHttpRequest();

    var total = 0;
    if($('#p1').val() && $('#qty').val()){
        var price = $('#p1').val();
        var qty = $('#qty').val();
        total += price * qty;
    }
    $('#total').val(total);
}
</script>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Joe Doe
  • 193
  • 1
  • 5
  • 13
  • 2
    do you see any console log errors ? – karthikr Dec 16 '14 at 18:40
  • Do you have a more complete example? http://jsbin.com/lereyaloza/1/ works for me. – chsh Dec 16 '14 at 18:43
  • 4
    Are you loading jQuery before or after that code snippet? You need to load it before for that to work. – Stryner Dec 16 '14 at 18:50
  • 1
    What troubleshooting have you done? What errors are showing in your console? Where is the relevant HTML? Why do you think the function is not working? What is supposed to happen vs. what's happening? Where did you include jQuery, before or after this code? – Sparky Dec 16 '14 at 18:53
  • Ninsly, that was the problem, I was loading jQuety after the code, thanks for that – Joe Doe Dec 16 '14 at 18:55

2 Answers2

2

You need to load jQuery before your script runs.

<!-- Put jQuery Here -->
<script>
    $(document).ready(function() {
        calculation();
    });

    //etc...
</script>

The reason that your code was working previously is because you were using jQuery inside a function that was being triggered by a button. That code would never run until the button was clicked, which was happening after your browser loaded jQuery.

Stryner
  • 7,288
  • 3
  • 18
  • 18
-2

Your Error is happening because you are using the READY function.

here is a bit of code thats causing issue:

if($('#p1').val() && $('#qty').val()){
        var price = $('#p1').val();
        var qty = $('#qty').val();
        total += price * qty;
    }
    $('#total').val(total);

you are attempting to get some HTML element data...but guess what? your HTML hasnt been loaded yet.

you want to use the onLoad event.

here is the difference between ready/onload:

window.onload vs $(document).ready()

Community
  • 1
  • 1
Nate
  • 1,630
  • 2
  • 24
  • 41