0
I’m developing a calculator on HTML + Jquery where I have the basic operations for it, but need to implement the following:
When the user type in the field input a kind of expression: (5*5)+4 the Jquery would have to take this value to perform the operation and show the result. any idea how it might be doing this ?
$("input[name=exp]").click(function(){
valor = $("#result").val();
$("#result").val(valor);
});
follows my code Jquery :
$( function(){
var v1, v2, op;
$("input[name=btn]").click(function(){
$("#result").val($("#result").val() + $(this).val());
});
$("input[name=ce]").click(function(){
$("#result").val('');
$("#op").text('');
});
$("input[name=soma]").click(function(){
if($("#result").val() != ''){
v1 = parseFloat($("#result").val());
$("#result").val('');
op = "soma";
$("#op").text($(this).val());
}else{
alert("Insira um valor para efetuar a operação");
}
});
$("input[name=menos]").click(function(){
if($("#result").val() != ''){
v1 = parseFloat($("#result").val());
$("#result").val('');
op = "menos";
$("#op").text($(this).val());
}else{
alert("Insira um valor para efetuar a operação");
}
});
$("input[name=vezes]").click(function(){
if($("#result").val() != ''){
v1 = parseFloat($("#result").val());
$("#result").val('');
op = "vezes";
$("#op").text($(this).val());
}else{
alert("Insira um valor para efetuar a operação");
}
});
$("input[name=divisao]").click(function(){
if($("#result").val() != ''){
v1 = parseFloat($("#result").val());
$("#result").val('');
op = "divisao";
$("#op").text($(this).val());
}else{
alert("Insira um valor para efetuar a operação");
}
});
$("input[name=igual]").click(function(){
if($("#result").val() != ''){
v2 = parseFloat($("#result").val());
if(op == "soma"){
$("#result").val(v1 + v2);
}else if(op == "menos"){
$("#result").val(v1 - v2);
}else if(op == "vezes"){
$("#result").val(v1 * v2);
}else{
$("#result").val(v1 / v2);
}
}else{
alert("Insira um valor para efetuar a operação");
}
});
$("input[name=apagar").click(function(){
var len = $("#result").val().length;
var valor = $("#result").val();
valor = valor.replace(valor.charAt(len - 1), "");
$("#result").val(valor);
});
});
Look, it is more practical to put all operation within a single input and use the function
eval()
to make the calculation:eval("(5*5)+4")
turns 29. The buttons would only be to insert the signals– RpgBoss
I can not use the function Val. I have to perform the operation without. Thanks more for the reply.
– Hejafe
So I think just with regular expression, the problem is that I don’t understand much of it.
– RpgBoss
I found the solution [link]https://stackoverflow.com/questions/49099008/calculate-expression-in-a-single-field-jquery/49113706#49113706[/link]
– Hejafe