javascript - 如何通过使用正则表达式更改值来获取单选按钮值的总和?

标签 javascript jquery html regex radio-button

我想添加所有单击的单选按钮的值,但我得到的数字不正确。

<div id="config">
    <input type="radio" name="brand" id="dell" value="Dell $1500"> Dell
    <input type="radio" name="brand" id="mackbookpro" value="MacbookPro $3000"> Macbook Pro
    <input type="radio" name="brand" id="asus" value="Asus $2000"> Asus

    <input type="radio" name="ram" id="4gb" value="4 Gb $60"> 4 GB RAM
    <input type="radio" name="ram" id="8gb" value="4 Gb $90"> 8 GB RAM
    <input type="radio" name="ram" id="16gb" value="4 Gb $125"> 16 GB RAM

    <input type="radio" name="storage" id="250gb" value="250 Gb $100"> 250 Gb Storage
    <input type="radio" name="storage" id="500gb" value="500 Gb $200"> 500 Gb Storage
    <input type="radio" name="storage" id="900gb" value="900 Gb $300"> 900 Gb Storage
</div>

<div id="show">0</div>

jQuery 看起来像这样

var displayPrice = document.getElementById('show');

$("#config input[type=radio]").click(function() {
    var total = 0;
    $("#config input[type=radio]:checked").each(function() {
        var checked = $(this).val();
        var checkNum = checked.split('$')[1];
        total += parseFloat(checkNum);
    });
    displayPrice.innerHTML = total;
});

我得到的数学结果加起来不正确。我做错了什么吗?

最佳答案

我稍微调整了一下,似乎工作正常:

$("#config").click("input[type=radio]",function() {
    var total = 0;

    $(this).parent().find('input[type=radio]').each(function() {
        var self = this;

        if(self.checked){
            total += parseFloat(self.value.split('$')[1]);
        }
    });

    alert(total);
});

Here is a jsFiddle for it .

关于javascript - 如何通过使用正则表达式更改值来获取单选按钮值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673499/

相关文章:

javascript - 如何在 iframe 中回发 aspx 页面?

javascript - 如何在 AJAX 成功时以编程方式关闭 Bootstrap 3 模式?

javascript - 处理程序在 "onchange"事件上不起作用

javascript - 查找具有最大值的父对象

javascript - 为什么使用 for 循环时表的格式错误?

jquery - $(window).width() 在缩放后不会更新(chrome IOS)

javascript - 当另一个 ul 被点击事件切换时关闭所有打开的 ul

javascript - jQuery 无法在不同的虚拟主机上运行

html - 无法选择(单击) float Div 中的 anchor 链接

javascript - html5/css3/javascript 中全功能文字处理器的可能性?