gpt4 book ai didi

javascript数组读取表单数据最佳实践

转载 作者:行者123 更新时间:2023-12-02 16:39:33 25 4
gpt4 key购买 nike

我对 JavaScript 还很陌生,想知道是否有更有效的方法来处理这种情况,例如使用数组?

我有一个包含 6 个字段的 HTML 表单,可让您输入过去六周支付的加类费金额。然后,我使用 javascript 将六个值相加,除以 6,再乘以 52,以获得每年的加类金额。我的字段名称为 w_ot_1、w_ot_2 到 w_ot_6,我使用下面的代码。一切都很好,但我发现它确实是重复的,而且我需要运行这个计算的不仅仅是加类。我确信必须有一种更有效的方法。有人有任何可以提供帮助的想法吗?

var weekly_ot_1 = parseFloat(document.getElementById("w_ot_1").value.replace(/[^0-9.]/g, ''));
var weekly_ot_2 = parseFloat(document.getElementById("w_ot_2").value.replace(/[^0-9.]/g, ''));
var weekly_ot_3 = parseFloat(document.getElementById("w_ot_3").value.replace(/[^0-9.]/g, ''));
var weekly_ot_4 = parseFloat(document.getElementById("w_ot_4").value.replace(/[^0-9.]/g, ''));
var weekly_ot_5 = parseFloat(document.getElementById("w_ot_5").value.replace(/[^0-9.]/g, ''));
var weekly_ot_6 = parseFloat(document.getElementById("w_ot_6").value.replace(/[^0-9.]/g, ''));
//weekly annualised overtime values
document.getElementById("w_annual_ot").value= addCommas((((weekly_ot_1 + weekly_ot_2 + weekly_ot_3 + weekly_ot_4 + weekly_ot_5 + weekly_ot_6)/6) * 52).toFixed(2));

最佳答案

在这种情况下,您可以在调用 document.getElementById() 时利用简单的 for 循环和字符串连接。我建议创建一个函数来计算加类费,并让该函数将周数作为参数,以便在添加更多字段时可以轻松更改它。

function getOvertimePaid(numberOfWeeks) {
var total = 0;

// Iterate from 1 to the number of weeks and increment the total by
// the parsed value in the field for the current index
for (var i=1; i<=numberOfWeeks; i++) {
total += parseFloat(document.getElementById('w_ot_' + i).value.replace(/[^0-9.]/g, '');
}

// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}

// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getOvertimePaid(6).toFixed(2));

为了使代码和支持的 HTML 更加灵活,您可能需要考虑的另一件事是在每周加类输入元素上利用类名称。如果您这样做并稍微调整代码,您可以随意添加或删除字段,并且计算年加类费的函数将继续工作。举个例子:

HTML

<input type="text" id="w_ot_1" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_2" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_3" class="weekly-overtime" value="0.00" />

JavaScript

function getAnnualizedValue(className) {
// Get all elements with the given class name
var elements = document.getElementsByClassName(className);

// Iterate the elements and keep a running total of their values
var total = 0;
for (var i = 0; i < elements.length; i++) {
total += parseFloat((elements[i].value || '0').replace(/[^0-9.]/g, '');
}

// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}

// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getAnnualizedValue('weekly-overtime').toFixed(2));

关于javascript数组读取表单数据最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27623241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com