How To Get Input Value With Cocoon And Javascript?
Solution 1:
First thing I noticed: in getUnitCost
you refer to gon
but I do not see how that is ever set or changed? But I assume that refers to a fixed value.
Then I see you have an cocoon:after-insert
callback, but I think at that stage the quantity is always empty?
However in your change
and keyup
events you make the same mistake: you no longer take into account which field actually triggered the change. On change
of any product-name
you clear all quantities?
So for instance, when the quantity changes, you have to use that specific quantity. Now you do $('.quantity').val()
which will return the value of the first quantity. So do something like
$(document).on('keyup', '.quantity', function() {
varthis = $(this);
var parent_nested_item = this.parent('.nested-fields');
var product_name = parent_nested_item.find(".product_name").val();
var q = this.val();
var p = getUnitCost(product_name);
var total = getTotal(p, q);
parent_nested_item.find('.total_price').val(total)
});
Note: this code is not tested, but an example to get you started.
In short, to recap: use the element that triggered the event ($(this)
) and then use the jquery dom traversal methods to find the correct items in the correct "scope".
Post a Comment for "How To Get Input Value With Cocoon And Javascript?"