Reputation: 173
I have a table and I want an "add row" function. What I'm doing is when the button is pressed the row is cloned then appened, and the id's, names of form elements, and onchange events are changed. All of this works except the onchange function always calls the latest id. So there are say 3 rows (id's 1, 2, and 3) and I trigger on change for row 2, row 3 gets passed to the handler instead of 2.
Here is the script:
function addRow(){
count = parseInt($("#hidden_count").val())
count++
$("#hidden_count").val(count)
var row = $("#add_box").prev().clone()
row.attr("id", "row_" + count)
row.children().each(function(index, elem){
if(elem.id.indexOf("delete_col_") != -1){
elem.id = "delete_col_" + count
$(elem).empty()
$(elem).append("<div class='table-row-delete' onclick='deleteRow("+count+")'></div>");
}else{
$(elem).children().each(function(index, elem){
if(typeof elem.name != 'undefined'){
if(elem.name.indexOf("exhaust_filter_num") != -1){
elem.name = "sheet[exhaust_filter_num_" + count + "]"
elem.value = parseInt(elem.value) + 1
}else if(elem.name.indexOf("exhaust_filter_size") != -1){
elem.name = "sheet[exhaust_filter_size_" + count + "]"
elem.id = "exhaust_filter_size_" + count
elem.onchange = function() { calculateRow(count) }
}else if(elem.name.indexOf("exhaust_velocity") != -1){
elem.name = "sheet[exhaust_velocity_" + count + "]"
elem.id = "exhaust_velocity_" + count
elem.value = 0
elem.onchange = function() { calculateRow(count) }
}else if(elem.name.indexOf("exhaust_cfm") != -1){
elem.name = "sheet[exhaust_cfm" + "_" + count + "]"
elem.id = "exhaust_cfm_" + count
elem.value = 0
}
}
})
}
})
row.insertBefore("#add_box")
}
function calculateRow(id){
var filter = $("#exhaust_filter_size_" + id).val()
console.log("Calc row: " + id + ", " + filter)
var velocity = parseInt($("#exhaust_velocity_" + id).val())
var cfmElem = $("#exhaust_cfm_" + id)
var cfm = velocity * filterData[filter].freeArea * filterData[filter].kFactor
cfmElem.val(cfm)
}
The orignal html is layed out like this (it is long so this is a stripped version):
<table>
<tr id="row_1">
<td><input onchanged="calculateRow(1)" /></td>
...
</tr>
<tr id="add_box" align="center">
<td colspan="5"><input type="button" value="Add Row" onclick="addRow();"/></td>
<input type="hidden" id="hidden_count" value="1" />
</tr>
</table>
Upvotes: 0
Views: 224
Reputation: 781058
You need to make count
a local variable with the var
keyword:
var count = parseInt($("#hidden_count").val());
Upvotes: 1