I'm coding a calculator and I'm trying to get the "." that is the value assigned to a button. When click on the button I want to put the value of the button in a variable and then I show it in the content of a div.
For numbers I retrieve the result but for "." not happen.
Here is the link to my codepen work: [javascript calculator][1]
$('button').click(function(){
input = $(this).val();
if (!isNaN(eval(input)) || input === "."){
console.log("input: "+input);
current += input;
log = current;
result += input;
$("#answer").text(current);
$("#history").text(result);
}
});
Value is only associated with input elements, So .val() will not give you the value attribute of button. But since a button value is an attribute you need to use the .attr() method in jquery. This should do it
<script type="text/javascript">
$('button').click(function(){
input = $(this).attr("value")
if (input === "." || !isNaN(eval(input))){
console.log("input: "+input);
current += input;
log = current;
result += input;
$("#answer").text(current);
$("#history").text(result);
}
});
</script>
$('button').click(function(){
var input = $(this).attr("value")
if ( input === "." || !isNaN(eval(input))){
console.log("input: "+input);
}
});
It is failing for you because when you test `!isNan(eval(input))` where `input = "."` your code breaks. change it to `if ( input === "." || !isNaN(eval(input))){`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value = ".">Hello</button>
Problem: Since button element is not of type input you will not be able to get its value by just using .val() on the element.
Solution:
Use .attr on the button to get the data in the value attribute
input = $(this).attr('value');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With