2012-08-29 1408 views
1

這是一個稍微簡化的問題版本,以便於解釋和縮短問題。從複選框選擇的表單人口

我有X複選框:

<input type="checkbox" class="checker" value="1" /> 
<input type="checkbox" class="checker" value="2" /> 
<input type="checkbox" class="checker" value="3" /> 
... 

我有2列,證書和成本,輸入字段的Y個(X> Y),那麼,總在底部:

<input type="text" class="cert" /><input type="text" class="cost"> 
<input type="text" class="cert" /><input type="text" class="cost"> 
<input type="text" class="cert" /><input type="text" class="cost"> 
... 

<input type="text" id="total" /> 

用戶可以選擇複選框的任意組合(最多限制Y)。當一個複選框被選中時,它的值被輸入到第一個空的證書輸入中。根據證書價值,相應的成本被放入相鄰的成本輸入(例如,證書1 =成本50,證書2 =成本100等)。

如果未勾選複選框,則相應的證書將被清除,成本也會被清除。

底部的總數保持對任何事物的變化的總運行總數。

幾個附加的註釋:

  • 的複選框在整個形式間隔開,而不是在一個連續的序列。
  • 同樣,證書和成本輸入並不實際上並排在html中(雖然看起來像在屏幕上),但它們之間還有其他代碼。

任何幫助/輸入非常感謝,因爲我大多隻是製造一團糟!

+1

所以...有什麼問題嗎? – Polyov

+0

你有沒有給你的輸入元素ID?這可能是您能夠區分彼此的第一步。 –

+0

你能告訴我們你試過什麼嗎? – Touki

回答

1

這裏有一些東西讓你開始。我不確定您的cert 1cert 2是在文本框內還是存在標籤或其他內容。與您的成本相同。但這就是我在示例中做到的方式。假設您具有與該組輸入相同數量的複選框(證書號&成本);

$('input.checker').change(function(){ 
    // store the current index so we can pick which text input to change 
    var $i = $(this).index('input.checker'); 
    // put val in corresponding cert text input 
    $('input.cert').eq($i).val(this.checked ? 'cert ' + ($i+1) : ''); 
    // put val in corresponding .cost text input 
    $('input.cost').eq($i).val(this.checked ? 'cost ' + (50 * ($i+1)) : ''); 

    var total = 0; 
    // loop through the cost inputs and add up total 
    $('input.cost').each(function(i,v){ 
     total += (+$(v).val().replace('cost ','')); 
    }); 
    // insert total 
    $('#total').val(total); 
});​ 

EXAMPLE FIDDLE