I am trying to update a total when the value of one of the factors changes. I have created a jsFiddleand provided a comment on it (line 16). This is probably the easiest place to see the issue.
It's simple sums, so I have a table that looks something like this.
Row 1 | 100 | 5 |
Row 2 | 200 | 10 |
Totals | 300 | 15 |
Table cells in Row 1 and Row 2 contain text fields. Table cells in the total row contain html. The id's and names of the div's / inputs are auto generated (please see jsFiddle link for example).
Everything works fine the first time I change the input amounts, but I am having a hard time setting the value of the original element to the new sum. When I update the field a second time, the calculation contemplates the original value - which throws my sums off. I have tried both the jQuery and javascript methods and have also tried with a specific id (not $(this)) all to no avail. I am new to javascript so am probably missing something simple.
My javascript looks like this
window.formTable = $('#def-inv-table');
$('input.form-text').change(function() {
var currentId = $(this).attr('id');
var orgValue = this.getAttribute('value');
var newValue = this.value;
var changeAmount = newValue - orgValue;
var pieces = currentId.split(/\s*\-\s*/g);
var key = pieces[1];
var orgTotalString = window.formTable.find('#total-' + pieces[2]).html();
var orgTotal = Number(orgTotalString.replace(/[^0-9\.]+/g,""));
var newTotal = orgTotal + changeAmount;
window.formTable.find('#total-' + pieces[2]).css("background", "blue");
window.formTable.find('#total-' + pieces[2]).html(newTotal);
//Here is my problem. This is not updating. I have tried the javascript way
//with document.getElementbyId and the jQuery way. Neither sets the value.
$(this).val(newValue);
var testVal = $(this).val();
//alert(testVal);
});
Please let me know if you want me to paste the html. I am leaving it out since it is in jsFiddle.
ADDING HTML
<form name="test-form" id="test-form">
<div id="def-inv-table">
<table>
<tr>
<td>
<input type="text" id="no-413-invreturned" name="investments[413][invreturned]" value="3000.00" class="form-text">
</td>
<td>
<input type="text" id="no-413-commreturned" name="investments[413][commreturned]" value="23.42" class="form-text">
</td>
</tr>
<tr>
<td>
<input type="text" id="no-414-invreturned" name="investments[414][invreturned]" value="1000.00" class="form-text">
</td>
<td>
<input type="text" id="no-414-commreturned" name="investments[414][commreturned]" value="15.89" class="form-text">
</td>
</tr>
<tr>
<td id="total-invreturned">4,000.00</td>
<td id="total-commreturned">39.31</td>
</tr>
</table>
</div>
<form>
window.formTable.find('#total-' + pieces[2]).html(newTotal);with.htmlmethod. Try using only.val()method calls