如何通过使用regex更改值来获得单选按钮值的总和

How do I get the sum of radio button values by changing the values with regex?

本文关键字:单选按钮 regex 何通过      更新时间:2023-09-26

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

<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);
});

这里有一个jsFiddle。

将字符串dediPrice添加到数字total后,会生成字符串。

为了确保它的工作原理,也将dediPrice转换为数字:

var dediPrice = parseFloat(document.getElementById('show').innerHTML);

看小提琴:http://jsfiddle.net/66f4ay9L/1/

您的代码运行良好。数学计算得很好。只有几个建议:

  1. 更改而不是单击事件
  2. this.value而不是$(this).val()
  3. +已检查。split('$')并取消parseFloat

演示

$(function() {
    var displayPrice = $('#show')[0];
    $("#config input[type=radio]").on('change',function() {
        var total = 0;
        $("#config input[type=radio]:checked").each(function() {
            var checked = this.value;
            var checkNum = +checked.split('$')[1];
            total += checkNum;
        });
        displayPrice.innerHTML = total;
    });
});