dongwei9365 2011-05-03 11:46
浏览 19
已采纳

jquery复选框和单选按钮

I currently have this code which calculates the total value of checkboxes when they are checked. I need to know how how I would add a radio button selection to this calculation. I need to do this as it adds a total and displays it live.

$(document).ready(function() {
    function recalculate() {
        var sum = 0;
        var base = 0;

        $("input[type=checkbox]:checked").each(function() {
             sum += parseInt($(this).attr("rel"));
        });

        $("#output").html(sum);
    }

    $("input[type=checkbox]").change(function() {
        recalculate();
    });

});


    <td width="236" height="25" align="left">Booking Period:</td>
</tr>
            <tr>
                <td height="10" align="right" class="align_left">One Day: ₤49 </td>
                <td>
                  <input type="radio" name="duration" id="oneday" value="One Day Rental"/>
                </td>
              </tr>

    <tr>
                <td height="30" align="right" class="align_right">Two Day: ₤69</td>
                <td>
                  <input type="radio" name="duration" id="two" value="Two Day Rental"/>
                </td>
              </tr>
    <tr>
                <td height="30" align="right" class="align_right">Weekend: ₤79</td>
                <td>
                  <input type="radio" name="duration" id="weekend" value="Weekend Rental"/>
                </td>
              </tr>
  • 写回答

2条回答 默认 最新

  • duanjiebian6712 2011-05-03 11:54
    关注

    If there is only one radio button group on this page you can simply use :radio[name='duration']:checked to get the currently selected radio button.

    function recalculate() {
        var sum = 0;
        var base = 0;
    
        $("input[type=checkbox]:checked").each(function() {
             sum += parseInt($(this).attr("rel"), 10);
        });
    
        sum +=  parseInt($(":radio[name='duration']:checked").attr("rel"), 10);  // or some attribute that has the price
        $("#output").html(sum);
    }
    

    And than to trigger the recalculate simply add the :radio[name='duration'] selector:

    $("input[type=checkbox], :radio[name='duration']").change(function() {
        recalculate();
    });
    

    Side note, you should include the radix in parseInt(, 10) to be on the safe side.

    Example on jsfiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao