【问题标题】:Form calculator using Each() and Children() in jQuery在 jQuery 中使用 Each() 和 Children() 的表单计算器
【发布时间】:2009-10-19 17:53:53
【问题描述】:

我正在尝试构建一个表单,该表单根据一系列带有字符串值的下拉框计算总价,例如“此选项花费 30 英镑”,我知道这并不理想,但我将其放在一起作为 hack现有脚本

在大多数情况下,我得到了它的工作,但我不确定如何为#productconfig 的每个子项运行每个函数

我可以手动将每个下拉列表的 id 输入到一个数组中,这样就可以进行计算,但如果它只与 #productconfig 的所有子项一起使用会很好

<code>

<div id="#productconfig">
<label>Model Type</label> 
<select name="products[220][data][modeltype]" id="data-modeltype-220">
    <option value="M-Type £500">M-Type £500</option>
    <option value="P-Type £500">P-Type £500</option>
    <option value="S-Type £500">S-Type £500</option>
</select>   
</div>
</code>

<code>
$(document).ready(function() {
$("#productconfig").children().change(function () {
    calculateoptions();
});
calculateoptions();
});
</code>
<code>
function calculateoptions() {

var arr = ["data-modeltype-220"];

var total = 0;

jQuery.each(arr, function () {
    var str = $('#' + this).attr("value");
    var poundsign = str.indexOf('£');
    var poundsign = poundsign + 1;
    var lengthofstr = str.length;
    var shortstr = str.substr(poundsign, lengthofstr);
    total = eval(total) + eval(shortstr);
});

$('#price').html("£" + total);

}
</code>

【问题讨论】:

  • &lt;div id="#productconfig"&gt; 应该是&lt;div id="productconfig"&gt;

标签: javascript jquery forms


【解决方案1】:

这个怎么样:

function calculateoptions() {

var total = 0;

jQuery('#productconfig select').each(function () {
        total += $(this).val().match(/£(\d+)/)[1];
});

$('#price').html("£" + total);

}

【讨论】:

  • 感谢 greg,这适用于我在函数中的旧代码。 total += $(this).val().match(/£(\d+)/)[1]; 这似乎不起作用。我认为它将值添加为字符串而不是数字。输出为 050000000060010000 英镑
【解决方案2】:

你可以使用:

 $("#productconfig select").each(function(){...});

选择产品配置 div 中的每个下拉菜单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多