Reputation: 3332
I have a short script that calculates a number by multiplying input
values. That script works fine but now I want to add if statements. For example:
HTML:
<label>Width</label><input type="text" id="width" />
<br>
<label>Length</label><input type="text" id="length" />
<br>
<label>Total</label><input type="text" id="total"/>
JavaScript:
var w = $('#width').val();
var l = $('#length').val();
var total1 = 2;
var total2 = 3;
if((w * l) > 5){
total = total1 * (w + l);
parseInt($('#total').val('total'));
}
if((w * l) < 5){
totalnew = total2 * (w + l);
parseInt($('#total').val(totalnew));
}
So if (#width x #length) > 5
, the value of (#width x #length)
would be multiplied by a certain number, in this case "2".
Tried to figure it out on jsfiddle.
Here is the code that works without the if statements: http://jsfiddle.net/e45SJ/
How can I implement what I am looking to achieve with the if statements with the code I already have?
EDIT: How can I add more than one if statement? I tried this: http://jsfiddle.net/m2LxV/2/
Upvotes: 2
Views: 3042
Reputation: 22984
Since the question asked to use your code to make the modification thats what I did. Not much has changed here and I commented any parts that might seem difficult.
function calculate()
{
//Parse the string value into an integer
var w = parseInt($('#width').val());
var l = parseInt($('#length').val());
var total1 = 2;
var total2 = 3;
//Perform IF
//suggestion to use an If {} Else
if((w * l) > 5)
{
//Set an internal value of total
var total = total1 * (w + l);
//Update the label's value to total
$('#total').val(total);
}
if((w * l) < 5)
{
//Same logic as above
var total = total2 * (w + l);
$('#total').val(total);
}
}
//Simple button event for testing
$('button').click(function()
{
calculate();
});
Some things to keep in mind
Upvotes: 2
Reputation: 388316
There are multiple problems
w + l
because both w
and l
are string valuesl + w
is 5 then none of your if
conditions are satisfied.parseInt($('#total').val('total'))
just assigns the value total
to the element and the parseInt
does not make any senseYou need to use a change handler
jQuery(function () {
var total1 = 2;
var total2 = 3;
$('#width, #length').change(function () {
var w = +$('#width').val();
var l = +$('#length').val();
var total;
if ((w * l) > 5) {
total = total1 * (w + l);
} else {
total = total2 * (w + l);
}
$('#total').val(total);
})
})
Demo: Fiddle
Upvotes: 5