I am trying to total a number of rows based on their name. It works fine as shown below…
var total = 0; $("input[name$='-line_item_january']").each(function(index, element) { var val = parseFloat($(element).val()); if (!isNaN(val)) { total += val; } }); $("#id_january_disabled_total").val((total).toFixed(2)); $("#id_january_total").val((total).toFixed(2));
I am now running into an issue whereby if the user hides the row…the value of the -line_item_january is still being included in my totals because the line_item_january is not hidden but the array is. From what I gather…from the rest of my program my best bet is to zero out the fields that are hidden in the array so that my computations are correct.
I tried to do something like…
$('[name=updatebudgetlineitem_set-1-line_item_january]').value = '0';
But it’s not working. Thanks in advance for any thoughts on what I might be doing incorrectly.
Advertisement
Answer
Depending on how your “rows” are structured, you can add :visible
to the selector, eg:
$("input[name$='-line_item_january']:visible").each(function(index, element) {
Alternatively, you can add/remove a class on the row/container and include that in the selector, eg:
$(".active input[name$=....`
Then when you hide the row, also remove that class from the container/row so that it affects all the inputs in the row/container – then the items that aren’t in an active row/container won’t be included.
Regarding setting the value=’0′ your line:
$('[name=updatebudgetlineitem_set-1-line_item_january]').value = '0';
mixes DOM methods and jquery, for jquery use .val("0")
$('[name=updatebudgetlineitem_set-1-line_item_january]').val("0")