Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event on button doesn't assign the value to a variable

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);
    }
});
like image 311
lisarko8077 Avatar asked Dec 20 '25 15:12

lisarko8077


2 Answers

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>
like image 81
Shubham Khatri Avatar answered Dec 23 '25 05:12

Shubham Khatri


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');
like image 29
Rajshekar Reddy Avatar answered Dec 23 '25 05:12

Rajshekar Reddy