g5wx
g5wx

Reputation: 720

Conditional math based on checkbox status

I have a script with a simple formula:

Input 1 * Input 2 * Input 3 / 25 = result

How can I manipulate the value 25 if a checbox is checked?

For example, if a checkbox is checked, the input 1,2,3 should divide with 35 at the end instead of 25 and display the result divided by 35.

Sample fiddle.

Upvotes: 0

Views: 230

Answers (5)

blablabla
blablabla

Reputation: 1478

function calculate() {
    var myBox1 = document.getElementById('box1').value; 
    var myBox2 = document.getElementById('box2').value;
    var myBox3 = document.getElementById('box3').value;
    var result = document.getElementById('result');
    var divide = (document.getElementById('changeValue').checked ? 35 : 25);
    var myResult = myBox1 * myBox2 * myBox3 / divide;
    result.value = myResult.toFixed(2) + ' eggs';
}

Upvotes: 2

Michal Kucaj
Michal Kucaj

Reputation: 691

function calculate() {
    var myBox1 = document.getElementById('box1').value;   
    var myBox2 = document.getElementById('box2').value;
    var myBox3 = document.getElementById('box3').value;
    var result = document.getElementById('result');   
    var myResult = myBox1 * myBox2 * myBox3 / 25;
    result.value = myResult;   

    //set initial state
     $('#changeValue').change(function() {
         if($(this).is(":checked")) {
          var myDivide = myBox1 * myBox2 * myBox3 / 35;
          return result.value = myDivide; 
         }     
     });
}

Upvotes: 0

rm4
rm4

Reputation: 721

You can do it by adding:

var value = (document.getElementById('changeValue').checked)?35:25;

Like that:

function calculate() {
    var myBox1 = document.getElementById('box1').value; 
    var myBox2 = document.getElementById('box2').value;
    var myBox3 = document.getElementById('box3').value;
    var result = document.getElementById('result'); 
    var value = (document.getElementById('changeValue').checked)?35:25;
    var myResult = myBox1 * myBox2 * myBox3 / value;
    result.value = myResult;    
}

Upvotes: 0

epascarello
epascarello

Reputation: 207511

Basic check to see if a checkbox is checked.

var isChecked = document.getElementById("changeValue").checked;  //get boolean for checked
var num = isChecked ? 35 : 25;  //ternary operation

References: Conditional_Operator

Upvotes: 0

Dominique Fortin
Dominique Fortin

Reputation: 2238

Change

var myResult = myBox1 * myBox2 * myBox3 / 25;

for

var divisor = ((document.getElementById('changeValue').checked)?35:25);
var myResult = myBox1 * myBox2 * myBox3 / divisor ;

Upvotes: 0

Related Questions