我有一個表格,這是一個用php構建的表格,用於從數據庫中提取一堆信息。在這些中,我有一個複選框,單擊它時,將取得estimatedCost的值並將其引發到一個JavaScript函數中,該函數可以計算它並保持所有對象的運行總數被檢查。使用Javascript的高級複選框
我想要做的是創建一個全選和取消全選選項,它仍然會將所需的變量傳遞到其他JavaScript函數中。讓我用一些代碼演示:
這將繪製標題旁邊的複選框。
foreach($replace as $key => $value)
{
$jScript = 'onclick=\'calcTotals("'.$replace[$key]['estimatedCost'].'","'.$replace[$key]['optionItem_id_replaceOrRepair'].'","'.$replace[$key]['service_title'].'","'.$replace[$key]['maintenanceitem_id'].'");\'';
$checkbox = sprintf('<input type="checkBox" name="ids[]" id="%s" value="%s" %s>', $replace[$key]['maintenanceitem_id'], $replace[$key]['maintenanceitem_id'], $jScript).' ';
$replace[$key]['title'] = $checkbox.$replace[$key]['title'];
$replace[$key]['estimatedCost'] = $replace[$key]['estimatedCost'];
}
這是當前檢查所有,並取消所有鏈接:
echo '<a href="#" onClick=\'setCheckboxes("budgeting", true); return false;\'>Check All</a> | ';
echo '<a href="#" onClick=\'setCheckboxes("budgeting", false); return false;\'>Uncheck All</a>';
現在目前的職能,我有在javascript:
function setBudgetCheckboxes(the_form, do_check) {
var elts = (typeof(document.forms[the_form].elements['ids[]']) != 'undefined')
? document.forms[the_form].elements['ids[]']
: (typeof(document.forms[the_form].elements['ids[]']) != 'undefined')
? document.forms[the_form].elements['ids[]']
: document.forms[the_form].elements['ids[]'];
var elts_cnt = (typeof(elts.length) != 'undefined')
? elts.length
: 0;
if (elts_cnt) {
for (var i = 0; i < elts_cnt; i++) {
elts[i].checked = do_check;
var name = document.getElementById(name);
} // end for
} else {
elts.checked = do_check;
} // end if... else
return true;
}
的,另外,它處理點擊一次一個:
function calcTotals(amount, type, service, name) {
if(amount[0] == '$') {
amount = amount.substr(1,amount.length);
}
var id = type+"_"+service+"_selected";
var grand_id = "Grand_selected";
var grand_service_id = "Grand_"+service+"_selected";
var type_id = type+"_selected";
var checked = document.getElementById(name).checked;
var multiplier = -1;
if(checked) {
multiplier = 1;
}
amount = amount * multiplier;
addBudgetValue(amount, id);
addBudgetValue(amount, grand_id);
addBudgetValue(amount, grand_id+"_h");
addBudgetValue(amount, type_id);
addBudgetValue(amount, grand_service_id);
addBudgetValue(amount, grand_service_id+"_h");
}
function addBudgetValue(amount, id) {
var current_value = document.getElementById(id).innerHTML;
var curtmp = 0;
if(current_value == "$0") {
current_value = amount;
}
else {
curtmp = parseFloat(current_value.substr(1,current_value.length));
current_value = (curtmp+parseFloat(amount));
}
var newVal = "$"+Number(current_value).toFixed(2);
if(newVal == "$0.00")
newVal = "$0";
document.getElementById(id).innerHTML = newVal;
}
所以問題是這樣的:你如何獲得全部檢查以檢查所有框,並將信息傳遞到calcTotals函數中,以便正確添加值?
您可以通過描述您從當前的「全部檢查」方法中看到的行爲,讓我們更輕鬆地解釋所有上述代碼嗎?你熟悉jQuery嗎? – JellicleCat
當您一次選擇一個複選框時,它會將estimatedCost值添加到當前運行成本中,並將其顯示在頁面上的浮動表中。它會根據選擇和取消選擇項目而上下移動。檢查所有鏈接將檢查所有的框,但不會加起來所有的成本。(作爲副作用,您可以手動取消選擇複選框,並且成本開始變爲負值。) – IceBlueFire