0

I have this script from fiddle:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
    $('#qty').keyup(function(){
    if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
    {
    var price = $('#real_price').val() * 1;
    var qty = $(this).val() * 1;

    var total = price * qty;
    $('#price').html(total);
    }
    else
    {
        $('#price').html(price);    
    }
    });

    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
    </script>

</head>
<body>
Price $<span id="price">500</span>
<input type="hidden" id="real_price" value="500" />
<input type="text" id="qty" value="1"/>
</body>
</html>

On fiddle it works, for me doesn't.

I've tried to add more quantities but it doesn't update the price. What could be the problem?

marius
  • 21
  • 8
  • Use `$('body').on('keyup', '#qty', function(){});` or place your code after elements you want to access or wrap them in DOM ready statement – arma Nov 28 '13 at 18:25
  • related: [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Felix Kling Nov 28 '13 at 18:27
  • Also, please read the [jQuery tutorial](http://learn.jquery.com/about-jquery/how-jquery-works/), it's explained there: *"To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the [ready event](http://api.jquery.com/ready/)"*. – Felix Kling Nov 28 '13 at 18:29

2 Answers2

1

That's because when the script is executed, the element doesn't exist yet so $('#qty').keyup... does nothing.

The simplest solution is to put the script at the end of the body.

The reason it works on fiddle is because usually the script is wrapped in a document ready event handler. Which brings us to the alternate solution : wrap all your code like this :

$(function(){
   your code here
});

but if your code isn't in an external file, simply putting it at the end of the body is enough.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
  • Ok, i tried to update the same value for another product but it works only for the first one. how can i update the second one? – marius Nov 29 '13 at 13:32
  • @marius Your comment isn't clear but it looks like you should ask another question (with code and maybe fiddle). – Denys Séguret Nov 29 '13 at 13:33
  • It's the same code, but with a new price field introduced. I'm a javascript newbie, so I'm a little confused with it... – marius Nov 29 '13 at 13:35
0

You could also try putting you function within this function:

$(document).ready(function() {

original function here

});

This usually solves allot of these problems for me.

J2D8T
  • 759
  • 9
  • 23