0

I have some sort of calculator, and I need to insert .num-pad_number.html() into my input. Is that correct way to do this:

$("#num-pad").on("click", ".num-pad_number", function (event) {
    $("#calc-input").val($("#calc-input").val() + $(this).html());
});

Or it may be more convinient and correct way? Cuz I have some bug with that solution. After some manipulations with websockets, "calculator" starts to duplicate every number, for example I need "5" but it insert "55".

7
  • Input.val() and $(this).html() both gives you an string of a number and by default they join as string not sum like numbers. '5' + '5' = '55' not 10; Commented Jul 6, 2017 at 22:36
  • You want to append the value of the button that's being clicked? Commented Jul 6, 2017 at 22:36
  • Use .text() not .html() since you won't be adding HTML, only the text content. Commented Jul 6, 2017 at 22:37
  • @Gustaf Gunér Yes! Commented Jul 6, 2017 at 22:38
  • @Farid Naderi yeah, I need to append numbers. Commented Jul 6, 2017 at 22:39

1 Answer 1

1

Slightly modified. Using .text() instead of .html(). Shorter event function. Working example below:

$('#num_pad .num-pad_number').click(function() {
  $("#calc-input").val($("#calc-input").val() + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="calc-input" type="text"/>

<div id="num_pad">
  <button class="num-pad_number">1</button>
  <button class="num-pad_number">2</button>
  <button class="num-pad_number">3</button>
  <button class="num-pad_number">4</button>
  <button class="num-pad_number">5</button>
  <button class="num-pad_number">6</button>
  <button class="num-pad_number">7</button>
  <button class="num-pad_number">8</button>
  <button class="num-pad_number">9</button>
</div>

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

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.