i have the below code which i’m unable to populate the total field in each individual row of elements.
So each field dynamically inserted will have the same fields, i just need to calculate the fields within that row only.
Here is the jsfiddle for it http://jsfiddle.net/glennmartin/3TnyR/
var LabourItems = {
rate: null,
hours: null,
total: null,
init: function(object) {
var rate = parseInt($(object).children('.rate').val(), 10);
// var rate = $(object).children('.rate').first();
var hours =parseInt($(object).children('.hours').val(), 10);
this.total = Number(rate.val()) * Number(hours.val());
this.updateTotal(object);
},
updateTotal: function(object) {
$(object).children('.total').first().attr('value', this.total)
}
}
//reactTochange for those inputs that you want to observe
$('.hours').on("click", function() {
jQuery.each($('.labouritems'), function(key,value){
LabourItems.init(value);
});
});
Here is your code working:
Here’s some comments about the changes I’ve made:
initfunction you were usingvarto assing to variables that you’ve declared in the context of your object, so I’ve replacedvar rateandvar hourswiththis.rateandthis.hours$(object).children('.rate')and$(object).children('.hours')calls you needed to use.first()function to get the first element selected. This is because you are selecting by a class name which there may be more than one of (even if there isn’t you’ll find you’ll still be returned with an array)$(object).children('.total').first().val(this.total || 0);: You can useval()to assign just like you have used it to retrieve the value, elsewhere.this.totalreturnsNaNwhen the textbox is empty so|| 0ensures that ifNaNever appears (it is falsy) then 0 will be used instead (remove it and see what happens if you’re curious)keydownevent. Of course, you can change this to anything you like.this.totalyou were usingNumber()which was unnecessary because those values have already been passed throughparseInt()each()function called from a$()DOM selectorthisprovides the element in this iteration. SoLabourItems.init(this);passes the actual element toinitwhich is then used via$(object)See http://jsfiddle.net/3TnyR/1/
Well, that’s pretty much it!