Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

radio button multiply, addition and multiplication of values

Does anyone know how to + and * selected radio values and display a result?

in the fiddle > itemOne + itemTwo * itemThree =

Managed to select the values and work out the maths, but struggling to bring it all together.

Many thanks for the time!

G

https://jsfiddle.net/omx617h8/

$(".itemOne").click(function() {
  var total = 0;
  $(".itemOne:checked").each(function() {
    total += parseInt($(this).val());
  })
  $("#total1").val(total);
});

$(".itemTwo").click(function() {
  var total = 0;
  $(".itemTwo:checked").each(function() {
    total += parseInt($(this).val());
  })
  $("#total2").val(total);
});

$(".itemThree").click(function() {
  var total = 0;
  $(".itemThree:checked").each(function() {
    total += parseInt($(this).val());
  })
  $("#total3").val(total);
});




var a = 5;
var b = 2;
var c = 2;
var z = (a + b) * c;
document.getElementById("calculation").innerHTML = z;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you are doing the same operation regardless of which radio button you click, you can use one function:

var total1 = $('#total1');
var total2 = $('#total2');
var total3 = $('#total3');

function updateValues() {
    // Get the selected values (default to zero if none selected).
    var val1 = parseInt($('.itemOne:checked').val()) || 0;
    var val2 = parseInt($('.itemTwo:checked').val()) || 0;
    var val3 = parseInt($('.itemThree:checked').val()) || 0;

    // Update the text inpus
    total1.val(val1);
    total2.val(val2);
    total3.val(val3);

    // Do calculation:
    var calculation = (val1 + val2) * val3;

    // Update your output:
    document.getElementById('calculation').innerHTML = calculation;
}

// Use this whenever a radio changes
$('[type="radio"]').on('click', updateValues);

You won't need the inline onclick attributes in your HTML with this either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...