Jquery 如何从多个无线电输入中添加值

Jquery 如何从多个无线电输入中添加值,jquery,radio-button,Jquery,Radio Button,我有两种形式,我想得到这两种形式的值的加法。 示例:在第一季度我选择2,在第二季度我选择4,在我的课堂结果中我想显示6。 解决方案也应与30个表单一起使用:) HTML <div class="q1"> <form> <input type="radio" name="q1" value="1"> 1 <input type="radio" name="q1" value="2">

我有两种形式,我想得到这两种形式的值的加法。 示例:在第一季度我选择2,在第二季度我选择4,在我的课堂结果中我想显示6。 解决方案也应与30个表单一起使用:)

HTML

<div class="q1">
  <form>
    <input type="radio" name="q1" value="1"> 1                       
    <input type="radio" name="q1" value="2"> 2                       
    <input type="radio" name="q1" value="3"> 3
    <input type="radio" name="q1" value="4"> 4
  </form>
</div>

<div class="q2">
  <form>
    <input type="radio" name="q2" value="1"> 1                       
    <input type="radio" name="q2" value="2"> 2                       
    <input type="radio" name="q2" value="3"> 3
    <input type="radio" name="q2" value="4"> 4
  </form>
</div>

<div class="result"></div>

我建议在
.q1
.q2
包装元素中添加一个通用类名,然后:

var $inputs = $('.question input[type=radio]').on('change', function () {
    var total = 0;
    $inputs.filter(':checked').each(function() {
        total += +this.value;
    });

    $('.result').text(total);
});

我个人建议:

// binding a change-event handler to inputs of type radio:
$('input[type="radio"]').on('change', function(){
    // setting the text of .result:
    $('.result').text(function(){
        // iterating over the checked radios whose name begins with 'q':
        return $('input[type="radio"][name^="q"]:checked').map(
            function(){
                // returning the value of the current input, as a number:
                return +(this.value || 0);
            // converting the map into an array, and reducing the array into:
            }).get().reduce(function (a, b) {
            // the sum of the numbers of the array:
            return a + b;
        });
    });
});

参考资料:

  • 数组:
  • jQuery:
    • 类似这样的东西:

      var r1=0, r2=0; 
      $('.q1').on('click',function(){
          r1 = parseInt($('input[name=q1]:checked').val());
          $('.result').html( r1 + r2);
      });
      
      $('.q2').on('click',function(){
          r2 = parseInt($('input[name=q2]:checked').val());   
          $('.result').html( r1 + r2);
      });
      

      确保为
      parseInt
      方法传入基数参数。默认以10为基数,但更安全。谢谢!为什么使用10作为默认值更安全呢?MDN建议始终传递基数。非常聪明。谢谢你的回答。
      var r1=0, r2=0; 
      $('.q1').on('click',function(){
          r1 = parseInt($('input[name=q1]:checked').val());
          $('.result').html( r1 + r2);
      });
      
      $('.q2').on('click',function(){
          r2 = parseInt($('input[name=q2]:checked').val());   
          $('.result').html( r1 + r2);
      });