【问题标题】:How add values from multiple radio input如何从多个无线电输入中添加值
【发布时间】:2014-10-26 06:17:22
【问题描述】:

我有 2 个表格,我想获得这 2 个表格的相加值。 示例:在 q1 我选择 2,在 q2 我选择 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>

jQuery

我得到了值,但我无法添加它们。

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

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

JSFiddle

【问题讨论】:

    标签: jquery radio-button


    【解决方案1】:

    我建议在 .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);
    });
    

    http://jsfiddle.net/t2fjnxcd/

    【讨论】:

      【解决方案2】:

      类似这样的:

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

      【讨论】:

      【解决方案3】:

      我个人建议:

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

      JS Fiddle demo.

      参考资料:

      【讨论】:

      • 非常聪明。感谢您的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2020-05-10
      相关资源
      最近更新 更多