Frank Kluytmans
Frank Kluytmans

Reputation: 543

Product price calculator isn't working

I'm creating an order form in which users can select an amount of products and it should immediately change total prices. I made some HTML markup and jquery code to achieve this, but I can't get it working. Can anyone see what I'm doing wrong?

Upvotes: 1

Views: 86

Answers (1)

dfsq
dfsq

Reputation: 193301

Fixed script:

$("input[type=number]").change(function () {
    var value = parseFloat($(this).attr("title"));
    var total = (value * this.value).toFixed(2);
    if (total < 0) total = 0;
    $(this).parent().next().find("input").val('€' + total);
});

Inside of event handler this refers to HTMLInputElement, not jQuery instance so you have to wrap it in $(this).

Also you need to traverse one level up to the parent node and then use next() to get target input field.

Finally I added basic validation to prevent negative prices. You can also add min="0" attribute to input fields.

Demo: http://jsfiddle.net/dfsq/X33pS/

Upvotes: 3

Related Questions