2017-10-16 72 views
0

我已經創建了一個動態表,其中生成了多行,並且在每行內部我都有一個模態和形式包含在模態中。每個模態形式都有唯一的ID。現在我想在禁用的文本字段中顯示兩個變量的結果。那麼,我該怎麼做?請幫助我。如果動態生成多行,如何在jQuery中添加兩個變量?

$(document).ready(function(){ 
    var a = parseInt($('#unit_rate'+this.id).val()); 
    var b = parseInt($('#tax'+this.id).val()); 
    var total = a+b; 
    $('#price').val(total); 
}); 
<input type="text" name="unit_rate" id="unit_rate<?php echo $product_id; ?>" value=""> 
<input type="text" name="tax" id="tax<?php echo $product_id; ?>" value=""> 
<input type="text" name="price" id="price<?php echo $product_id; ?>" value=""> 

謝謝

+0

在使用this.id中定義「id」的地方 –

+0

問題是'this.id'是'undefined'。 – George

+0

鑑於'this'是指'window',你期待'this.id'返回什麼? –

回答

0

你行是動態生成的,使他們不DOM的一部分被加載頁面時。要選擇一個特定的行使用document.getElementById

下面是一個簡單的演示:

var id=1; 
 
$("body").append('<input type="text" name="unit_rate" id="unit_rate1" value=""><input type="text" name="tax" id="tax1" value=""><input type="text" name="price" id="price" value="">'); 
 

 
$("button").on("click",function(){ 
 
    var a = parseInt($(document.getElementById('unit_rate'+id)).val()); 
 
    var b = parseInt($(document.getElementById('tax'+id)).val()); 
 
    var total = a+b; 
 
    console.log(total); 
 
    $(document.getElementById('price')).val(total); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button typ="button" >Sum</button>

0

我會一個類分配給你想要得到的值的所有元素(這不會是動態生成)。 然後你可以選擇所有這些元素 - $(「。my_class_here」) - 並用$ .each()遍歷你的選擇,讀取值並將它們相加。

按照你的例子:

$(document).ready(function(){ 
    var total=0; 
    var elements = $(".test"); 
    $.each(elements, function(key, value) { 
     total += parseInt(value.value, 10); 
    }); 
    $('#price').val(total); 
}); 

<input type="text" name="unit_rate" id="unit_rate1" class="test" value="20"><br> 
<input type="text" name="tax" id="tax2" class="test" value="50"><br> 
<input type="text" name="price" id="price" value=""> 

熊記住,jQuery是返回HTML對象,因此我們需要使用.value而不是.val()得到的數量。另外,由於您使用了文本輸入,因此我們需要使用parseInt()來獲取實際的數字,而不是字段中的字符串。

相關問題