2013-06-06 51 views
5

Tôi muốn tạo biểu mẫu trong đó tôi có 7 trường nhập, trong đó tôi nhập số và một trường nhập cuối cùng trong đó tất cả các số được chèn được tổng kết trong một kết quả. Tôi đã cố gắng chỉnh sửa một số tập lệnh từ trình xếp chồng khác nhưng từ một số lý do khiến nó không hiển thị kết quả.jquery tổng của nhiều trường nhập trong một

html là:

<form class="form-horizontal" id="whereEntry" method='post' action=''> 
    <fieldset> 
    <input type="text" class="income_count span1 register_input" id="income" name="income" placeholder="% of income"> <br> 
    <input type="text" class="income_count span1 register_input" id="income_2" name="income_2" placeholder="% of income"> <br> 
<input type="text" class="income_count span1 register_input" id="income_3" name="income_3" placeholder="% of income"> <br> 
<input type="text" class="income_count span1 register_input" id="income_4" name="income_4" placeholder="% of income"> <br> 
    <input type="text" class="income_count span1 register_input" id="income_5" name="income_5" placeholder="% of income"> <br> 
     <input type="text" class="income_count span1 register_input" id="income_6" name="income_6" placeholder="% of income"> <br><br><br> 

    <input type="text" class="span2 register_input" id="income_sum" name="income_sum" placeholder="% of income"> <br> 
     </fieldset> 
     </form> 

và kịch bản của tôi cho đến nay trông như thế này:

var $form = $('#whereEntry'), 
$summands = $form.find('.income_count'), 
$sumDisplay = $('#income_sum'); 

$form.delegate('.income_count', 'change', function() 
{ 
var sum = 0; 
$summands.each(function() 
{ 
    var value = Number($(this).val()); 
    if (!isNaN(value)) sum += value; 
}); 

$sumDisplay.text(sum); 
}); 

đây là jsfiddle của nó: http://jsfiddle.net/bT4nm/1/

thể bạn giúp tôi? là vấn đề trong lớp học html của tôi hay cái gì trong kịch bản tôi nooby về jQuery và tôi cần là càng sớm càng tốt giải pháp .. cập nhật của js của tôi fiddle sẽ là tuyệt vời

+0

Khi bạn nhận được các số tổng hợp chính xác, bạn có thể gặp khó khăn khi hiển thị tổng số với định dạng chính xác (nghìn dấu tách, số thập phân, ký hiệu tiền tệ, v.v.). Xem câu trả lời này để được trợ giúp về điều đó: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript/28378652#28378652 – gibberish

Trả lời

5

Sử dụng này:

var $form = $('#whereEntry'), 
$summands = $form.find('.income_count'), 
$sumDisplay = $('#income_sum'); 

$form.delegate('.income_count', 'change', function() 
{ 
var sum = 0; 
$summands.each(function() 
{ 
    var value = Number($(this).val()); 
    if (!isNaN(value)) sum += value; 
}); 

$sumDisplay.val(sum); 
}); 
+0

cũng xin cảm ơn ! :) – dzordz