Reputation: 233
I need to make a calculator on jquery that does the basic operations (+, -, *, /). The operands are taken from a form input and the operation from a form select. The result is printed on a form label. At this point it sums the 2 values which any of the options selected. Heres my code:
$('document').ready(function(){
var op = $( "#operacion" ).val();
if ( op == "suma") {
$('#calcular').click(function(){
suma = parseFloat($('#operador1').val()) + parseFloat($('#operador2').val());
$("#res").text(suma);
});
}
else if ( op == "resta") {
$('#calcular').click(function(){
resta = parseFloat($('#operador1').val()) - parseFloat($('#operador2').val());
$("#res").text(resta);
});
}
else if ( op == "multiplicacion") {
$('#calcular').click(function(){
multiplicacion = parseFloat($('#operador1').val()) * parseFloat($('#operador2').val());
$("#res").text(multiplicacion);
});
}
else {
$('#calcular').click(function(){
division = parseFloat($('#operador1').val()) / parseFloat($('#operador2').val());
$("#res").text(division);
});
}
});
Upvotes: 0
Views: 160
Reputation: 192
You have to check the "op" inside of the click function. Something like:
$('document').ready(function(){
$('#calcular').click(function(){
var op = $( "#operacion" ).val();
var result;
if ( op == "suma") {
result = parseFloat($('#operador1').val()) + parseFloat($('#operador2').val());
}
else if ( op == "resta") {
result = parseFloat($('#operador1').val()) - parseFloat($('#operador2').val());
}
// ....
$('#res').text(result);
});
});
Reason: you save the operator at page load, which is always the first element in the select (if not other is selected by attribute).
Upvotes: 1