Not able to get value using Keyup event for input field and to display sum of two fields


#1

Hi,What I try to accomplish here is when I type in some number on “modelBid” field it add itself with the foodmin field, then displays total inside text {{TotalBiddingCost}} . I’m aware that there’re several solutions out there but I wonder if this can be done using Meteor template helpers.

Please see the below code:

client.js
Template.vip_view.events({
‘onkeyup #modelBid’: function() {
var bid = parseInt($(’#modelBid’).val());
var foodcost = parseInt($(’#foodmin’).val());
var total = parseInt($(‘total’).val( bid + foodcost));
console.log(total)
Session.set(“TotalBiddingCost”, total);
return total;
}
});

Template.vip_view.helpers({

TotalBiddingCost:function(){
return Session.get(“TotalBiddingCost”);
}
});

{{> afQuickField name="modelBid" label="Enter Host Bid" type="afCurrencyType" }}
{{> afQuickField name="tableBid" label="Enter Table Bid" value=party.foodmin type="afCurrencyType"}}

“The total is {{TotalBiddingCost}} Click below to submit.”


#2

There are a few mistakes here:

  • 'onkeyup #modelBid'
    • The event is keyup.
    • You specify an id by using #modelBid, but autoform uses name.
  • parseInt
    • You should really specify the base. It’s not strictly optional, even though it usually works.
  • var foodcost = parseInt($(’#foodmin’).val())
    • There is no id-foodmin in your form. There is a name="tableBid".
  • var total = parseInt($(‘total’).val( bid + foodcost))
    • Does not make sense.
  • Session
    • I don’t like Session when you seem to have it scoped to the template.

Here’s what I used:

Template.vip_view.onCreated(function vip_viewOnCreated() {
  this.cost = new ReactiveVar(0);
});

Template.vip_view.events({
  'keyup input[name="modelBid"], keyup input[name="tableBid"]'(e, t) {
    const bid = parseInt($('input[name="modelBid"]').val(), 10) || 0;
    const foodcost = parseInt($('input[name="tableBid"]').val(), 10) || 0;
    const total = bid + foodcost;
    console.log(total)
    t.cost.set(total);
  }
});

Template.vip_view.helpers({
  TotalBiddingCost() {
    return Template.instance().cost.get();
  },
});