Reputation: 11
HTML User Input:
=110*200
jQuery:
$(document).on("change", ".calculator", function(){
var value = $(this).val();
if(value.charAt(0) == '='){
var newval = value.slice(1);
console.log(parseInt(newval));
}
})
Output:
110
Anyone can please tell me How can I perform maths operation by using this programme? Where am I going wrong And Why it not working?
Upvotes: 0
Views: 39
Reputation: 4475
This is happening because you never evaluate the expression itself. You cast string expression to integer, and it takes identifiable integer part from the expression, breaking it at * character.
Evaluate your expression with eval, and it will get calculated. Alternatively, you can also use Function construct as described in answer here to evaluate this expression.
$(document).on("change", ".calculator", function(){
var value = $(this).val();
console.log(value.charAt(0));
if(value.charAt(0) == '='){
var newval = value.slice(1);
console.log(parseInt(eval(newval)));
console.log(new Function('return ' + newval)());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="calculator" type="text">
Upvotes: 1