ruby on rails - Sum/ subtract dynamic element by id using jQuery -
i have order form user can add or remove tickets dynamically using ajax ( similar railscast #197 it's nested form). each ticket displays ticket price (a ruby instance variable - @event.ticket_price) class of 'price'.
i found snippet elsewhere adapted sum elements class 'price' , display result in div id 'total_price'
$('#total_price').html(function() { var = 0; $(".price").each(function() { += parseint($(this).html()); }); return a; });
this generates total price when add ticket link clicked when page loads shows nothing (it should have price of 1 ticket there default). when ticket removed need function subtract price of ticket total. lastly prefer price in dollars nan when this, guess need regex of kind?
new rails, newer jquery, appreciate this, thanks!
the remove ticket function
function remove_fields(link) { $(link).prev("input[type=hidden]").val("1"); $(link).closest(".fields").hide(); }
the add ticket function
function add_fields(link, association, content) { var new_id = new date().gettime(); var regexp = new regexp("new_" + association, "g") $(link).parent().before(content.replace(regexp, new_id)); }
for first question, i'm not sure structure of rest of code, price may not appearing depending on when javascript executed. suggest making function named 'displayprice' , pasting code there. call function when button clicked, , call when body loads so:
<body onload="displayprice()">
for removing ticket, remove object class 'price' , call 'displayprice' function again.
for dollar sign, set function return as
return '$' +
javascript should handle type conversion you.
Comments
Post a Comment