2014-11-10 2 views
0

동적으로 테이블 행을 생성하고이를 사용하여 수학 연산을 수행하려고합니다. 그러나 값의 업데이트가 작동하지 않습니다. HTML 테이블 :동적으로 생성 된 테이블 행에 입력 곱하기

<tr class="multLote"> 
<th><input type="text" name="lote[]" value="0"></th> 
<th><input type="text" name="lote100[]" class="val100" value="0"></th> 
<th><input type="text" name="lote50[]" class="val50" value="0"></th> 
<th><input type="text" name="lote20[]" class="val20" value="0"></th> 
<th><input type="text" name="lote10[]" class="val10" value="0"></th> 
<th><input type="text" disabled name="lote_result[]" class="lote_result" value="0"></th> 
</tr> 

이 표는 행 추가 jQuery를 사용

$('.add-box').click(function() { 
var box_html = $('<tr class="multLote"><th><input type="text" name="lote[]" value="0" /></th> ' + 
'<th><input type="text" name="lote100[]" value="0" class="val100" /></th>' + 
'<th><input type="text" name="lote50[]" value="0" class="val50" /></th>' + 
'<th><input type="text" name="lote20[]" value="0" class="val20" /></th>' + 
'<th><input type="text" name="lote10[]" value="0" class="val10" /></th>'+ 
'<th><input type="text" disabled name="lote_result[]" class="lote_result" value="0"></th>'+ 
'<th><a href="#" onclick="remover(this)" class="remove-box">Remover</a></th></tr>'); 

$('#tabela-lotes tbody').append(box_html); 
    return false; 
}); 

을 그리고이 jQuery를이 행의 입력 값을 곱 :

$(".multLote input").keyup(multInputs); 

function multInputs() {          
    var mult = 0; 
    // for each row: 
    $("tr.multLote").each(function() { 

    // get the values from this row: 
    var $val100 = $('.val100', this).val(); 
    var $val50 = $('.val50', this).val(); 
    var $val20 = $('.val20', this).val(); 
    var $val10 = $('.val10', this).val(); 
    var $total = ($val100 * 100) + ($val50 * 50) + ($val20 * 20) + ($val10 * 10); 
    // set total for the row 
    $('.lote_result', this).val($total); 
    mult += $total; 
    }); 

} 

을 그것은 단지에 작동 첫 번째 행, 생성되지 않은 행 맨 위 행의 모든 ​​변경 사항은 모든 행을 업데이트하지만, 우리가 원하는 것은 아닙니다. 리드가 있습니까?

+0

Q : 왜 당신은 더 많은 테이블 헤더가 아닌 TDS 파일을 추가하는? –

답변

1

위임 된 이벤트 처리기을 변경되지 않는 조상 요소에 첨부하십시오.

JSFiddle :http://jsfiddle.net/TrueBlueAussie/wowne0La/3/

예컨대

그것은 이벤트 시간에서의 jQuery 셀렉터를 적용하여 작동
$('#tabela-lotes').on("keyup", ".multLote input", multInputs); 

, 이벤트가되었다하지 않을 때 : 아마 #tabela-lotes을 사용하여 귀하의 경우, 그래서 아무 것도이 가까이없는 경우

$(document).on("keyup", ".multLote input", multInputs); 

document

은 기본입니다 등기. 즉, 해당 조상 요소 아래에 아직 존재하지 않는 항목에 대해 작업 할 수 있음을 의미합니다.

참고 :

  • 는 또한 발견하고는 현재 행을 축적하는 핸들러를 변경했습니다.
  • TH 요소를 TD으로 변경합니다. TH은 테이블 헤더 전용입니다.
  • remover 코드도 위임 된 이벤트로 처리 할 수 ​​있습니다. 속성 기반 이벤트 처리기는 jQuery와 함께 정말 나쁜 생각입니다.

리무버 코드 :

JSFiddle :http://jsfiddle.net/TrueBlueAussie/hrea9pw6/

$('#tabela-lotes').on('click', '.remove-box', function(e){ 
    e.preventDefault(); 
    $(this).closest('tr.multLote').remove(); 
}); 
+0

어느 쪽도 작동하지 않았습니다 ... –

+0

@ Ícaro Abreu : 몇 가지 변경 사항을 추가하고 JSFiddle을 제공했습니다. 즐겨. –

관련 문제