[英]How do I add up the vals of inputs using jquery?
我正在使用GPA計算器,但是遇到了障礙。
計算器的外觀如下: http : //codepen.io/m6cheung/pen/KdWGxa 。
這是其中的JS部分:
var $units = $('.units');
var $grade = $('.grade-select');
var $gpa = $('#gpa');
var sum = 0;
$('.btn').click(function() {
$('.block').last().clone().children().val("").parent().appendTo($('.inner-box'));
});
$('.result').hide();
$units.keyup(function() {
$gpa.text((($grade.val() * $(this).val()) / $(this).val()).toFixed(2));
});
$grade.change(function() {
$gpa.text((($units.val() * $(this).val()) / $units.val()).toFixed(2));
$('.result').show();
});
我想知道的是:還有其他方法,所以當我按下“ Add Course
按鈕時,可以使用jQuery來進一步操縱$units
和$grade
值嗎? 目前,它僅適用於第一組輸入值。
添加新行后, keyup
和change
事件未綁定到它們。
嘗試使用:-
$(document).on('keyup','.units', function() {
和
$(document).on('change','.grade-select', function() {
編輯評論
要添加它們,創建一個新函數:
function sumScores(){
var score = 0;
$('.block').each(function(i, element){
var unit = $(element).find('.units').val();
var grade = $(element).find('.grade-select').val();
// do calculation and add to score
});
$gpa.text(score.toFixed(2);
}
然后將該功能設置為keyup / change處理程序。
$(document).on('keyup','.units', sumScores);
$(document).on('change','.grade-select', sumScores);
我注意到您的代碼開頭是: var $units = $('.units');
您的輸入是通過克隆動態生成的。
您的計算僅在第一個輸入處起作用的一個原因是,$ input僅指向第一個輸入,與$ grade相同。
也許您期望$ input在克隆時會自動接受其他輸入。 事實並非如此。 它不能像CSS規則那樣工作。 您需要為每個克隆重新執行該行,如下所示:
$('.btn').click(function() {
$('.block').last().clone().children().val("").parent().appendTo($('.inner-box'));
$units = $('.units');
$grade = $('.grade-select');
});
要操縱所有值,您需要像這樣循環所有元素:
var sum = 0;
for (var n = 0; n < $units.length; n++) {
sum += 1 * $($units[n]).val();//1 * -> is for assurance it adding not concat
//to retreive $grade use $($grade[n]).val()
}
由於輸入是動態添加的,因此需要將事件綁定到最接近的靜態父級,例如.outer-box
。 由於事件冒泡,將其綁定到document
是不好的/代價很高的。 添加輸入就像編寫將在keyup
和change
調用的函數一樣容易,這也消除了代碼重復。
var $oBox = $('.outer-box'),
$gpa = $('#gpa'),
$result = $('.result').hide();
$('.btn').click(function() {
$('.block').last().clone().children().val("").parent().appendTo($('.inner-box'));
});
$oBox.on("keyup", ".units", function() {
$gpa.text(getTotal());
});
$oBox.on("change", ".grade-select", function() {
$gpa.text(getTotal());
//Show $result only if it's hidden
$result.is(":hidden") && $result.show();
});
//The function I stated above
function getTotal() {
var sum = 0;
//Loop thru the units
$('.units').each(function() {
var $this = $(this);
//You must also check if the entered unit is a number
//to avoid operating on non-number inputs
//https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
if ( !isNaN($this.val()) ) {
//Input vals are always of type string, so, convert them to numbers
//Multiply the pairs
sum += parseFloat($this.val()||0) * parseFloat($this.parent().find('.grade-select').val()||0);
}
});
//Format the number
return sum.toFixed(2);
}
您更新的筆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.