Nitol Biswas
Nitol Biswas

Reputation: 1

Jquery keyup() function not work properly

I'm a beggainer lavel in programming. What is the problem I can not find out. when I change the number. it's not working as I want.

html:

<tr>  
<td><?php echo $food ;?></td>  
<td id="price"><?php echo $price ;?></td>  
<td><input type="text" value="1" id="num"></td>  
<td id="total">50</td>  
<td><a href="#">X</a></td>  
</tr>

jQuery:

$('#num').keyup(function(){  
    var price = parseInt($('#price').val());  
    var num = parseInt($('#num').val());  
    price = price * num;  
    $('#total').html(price);
});

Upvotes: 0

Views: 273

Answers (3)

KJ Price
KJ Price

Reputation: 5984

<td id="price"> is a table cell and as such, you cannot access its value as you are trying to do here

var price = parseInt($('#price').val());  

.val() method is intended for input, select, and textarea elements, not td elements. You have a couple of options based on what you actually want to do. I suggest using .text instead of .val().

Also, it is good to note that you need to call .keyup() only after the element #num has loaded. To guarantee this, use $(document).ready(). Full javascript code is as follows:

$(document).ready(function(){
    $('#num').keyup(function(){  
        var price = parseInt($('#price').text());  
        var num = parseInt($('#num').val());  
        price = price * num;  
        $('#total').html(price);
    });
});

Upvotes: 2

David
David

Reputation: 219016

This won't return anything:

$('#price').val() // undefined

#price is a td element. td elements don't have a value. It does, however, have text:

$('#price').text() // the value you echo from PHP

Upvotes: 0

Ryan Harne
Ryan Harne

Reputation: 479

try wrap you event function in $(document).ready(), or move them in footer area.

Upvotes: 0

Related Questions