[英]How to add input field of a form with same class name
我有一個JavaScript問題,但仍然可以找到解決方法。
我有一個動態形成的表格,其中包含表格字段。
碼:
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
cell1.innerHTML = count; //this is index, set above as var count = 1;
cell2.innerHTML = name; //this is a variale dynamically generated
cell3.innerHTML = '<input type="text" name="quantity[]" onchange="addAll()" class="quantity" id="quantity" value="1" data-price="'+price+'" />'
cell4.innerHTML = price;
cell5.innerHTML = '<a href="#" onclick="deleteRow('+count+')">Delete</a>';
他上面將提出類似以下內容:
<input type="text" name="quantity[]" onchange="addAll()" class="quantity" value="1" data-price="4" />
<input type="text" name="quantity[]" onchange="addAll()" class="quantity" value="34" data-price="5" />
<input type="text" name="quantity[]" onchange="addAll()" class="quantity" value="12" data-price="8" />
然后我有另一個輸入標簽,標簽總數為
<input name="total" id="total" />
我想始終在每次onchange()之后遍歷上面的輸入表單並進行計算。
var total = class with quantity[0] * data-price + class with quantity[1] * data-price //and so on for all the input (multiply the input value by the data-price attribute and add all together).
所以我可以把它放在函數中:
function addAll() {
//code that returns the total
document.GetElementById('total').value = total;
}
我正在看jQuery $(“ className”)。each(function(),但確實讓我感到困惑
如果您想訪問每個類,則以下jquery可以做到:
var total=0;
$(".quantity").each(function() {
total=total+$(this).val();
});
“。” 表示“選擇類別”,就像使用CSS一樣。 您無法對id進行相同的操作,因為id的含義是唯一的,因此jquery將僅返回第一個元素。
您可以使用以下代碼遍歷您的字段:
$('。數量')。 each(function(){//您的計算});
function addAll()
{
var total = 0;
$('.quantity).each(function()
{
if($(this).attr('name')!='Total')
{
var val = $(this).attr('value')
var dat = $(this).attr('data-price')
total = total + (val*dat)
}
});
document.GetElementById('total').value = total
}
我相信這會滿足您的要求...盡管它沒有附加到.on('change')
事件上。 您可能需要自己更改一下。 祝您學習jQuery好運。
使用jQuery .each()
!
var value = 0, price = 0;
$('.quantity').each(function () {
var val = value += Number($(this).val()),
data = price += $(this).data('price'),
total = val * data;
$('#total').val(total);
});
JSFiddle示例 -您可能想看看...
我認為這是滿足您要求的完美代碼
$('.quantity').change(function(){
var total = 0;
$('.quantity').each(function(index,element){
total += ( $(element).val())*($(element).prop('data-price'));
});
$('#total').val(total);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.