简体   繁体   中英

Adding and Multiplying Radio button values with javascript

I have a survey form I developed and placed in jsfiddle http://jsfiddle.net/tMUJT/

$('input:radio').change(function(){ 
  var tot=0;
  $('input:radio:checked').each(function(){
    tot+=parseInt($(this).val());
  });
  tot+=parseInt($('#more').val());
    $('#usertotal').html(tot)
  });

  $('#more').change(function(){
    $('input:radio').trigger('change');
});

Each radio input has the value of 1.

I need to show the sum of each column beneath each column and then show a final sum based on the calculation below:

column1 total x 0 + column2 total x 1 + column3 total x 2 + column4 total x 3 + column5 total x 4 =

I tried re-purposing many scripts but just couldn't get it to work - my js skills aren't that great. If some could please help me make it work in jsfiddle, I'd be very grateful. Thanks!

http://jsfiddle.net/3qh8D/1/

I like to use html5 data attributes for this sort of thing. You can call it what you'd like but I used data-factor (actually weight would make more sense). I think it's better to put this into markup. That way when you generate the markup you can bind the value that you're looking for directly into the HTML rather than having some sort of mapping in your code somewhere that says "this css class is equal to 1 and this css class is equal to 2" etc.

<td bgcolor="#00CC66"><input type="radio" data-factor='1' name="checkbox" id="checkbox1" value="1"></td>
<td>On shelf</td>
<td bgcolor="#FFFF33"><input type="radio" data-factor='2' name="checkbox" id="checkbox2" value="1"></td>
<td>No</td>
<td bgcolor="#fba459"><input type="radio" data-factor='3' name="checkbox" id="checkbox3" value="1"></td>
<td class="dots">&nbsp;</td>

Then whenever one of the radio buttons changes you just roll through all the checked inputs and add up the data-factor values.

// column1 total x 0 + column2 total x 1 + column3 total x 2 + column4 total x 3 + column5 total x 4 =

$(':input[type=radio]').change(function() {
  var $inp, factor, inp, inputs, total, _i, _len;
  total = 0;
  inputs = $('input[type=radio]:checked');
  for (_i = 0, _len = inputs.length; _i < _len; _i++) {
    inp = inputs[_i];
    $inp = $(inp);
    factor = $inp.attr('data-factor') || 0;
    total += +factor;
  }
  return $('#totalValue').text("Total value:" + total);
});

(the fiddle is in coffeescript because I find that more readable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM