0

I am attempting to learn HTML and Javascript, and with this, I am working on building a simple calculator device, where all of the numbers and operators are buttons that are clicked, and the results are displayed in an input box. However I have had issues with, when clicking on the buttons, having the events trigger to display the selected numbers value in the box.

Here is my HTML and JS:

var numString = "";

$('.number').click(function() {  
  numString += $(this).val().toString;
  $('input[name=display]').val(numString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="display" name="display" disabled></input>
<button id="button1" class="number" value="1">1</button>

2
  • You have to clear inside click function like numString = "" else it will add whenever you click button Commented Sep 10, 2017 at 7:58
  • 2
    The toString should be toString() Commented Sep 10, 2017 at 7:58

2 Answers 2

2

Try with the below code . it should be .toString() instead of .toString

var numString = "";
$('.number').click(function() {
     numString += $(this).val().toString();
     $('input[name=display]').val(numString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="display" name="display" disabled></input>

<button id="button1" class="number" value="1">1</button>

Sign up to request clarification or add additional context in comments.

1 Comment

@Professor_Joykill did you try running the snippet above?
1

You have a type in $(this).val().toString toString is a function, I believe the intention was to call it like this $(this).val().toString()

After fixing toString, your code would produce 1 -> 11 -> 111...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.