Skip to content

How do I get this script to multiply a number that was typed into the input field?

I’m trying to pull the number that a user types into a text field and multiply that by a number that is already established. (There are other buttons that add +1 or subtract -1 from the total that work just fine. The only problem I’m having is this right here, getting a user’s input by them typing in a value to a field and pulling it)

Here’s my code:

<!-- HTML Field that I am trying to pull a number out of -->
<input type="text" id="multNumInput">

// Creative my variables
var number = 0;

// Creative a variable that is equal to whatever is inputted into the text box
var multNum = $("#multNumInput").val();

// On Button Click, take the number variable and multiply it times whatever the value was inputted in the html
$('#multiply').click(function(){
  number = number * multNum;
  $('result1').text(number);
  console.log(number);
})

Hopefully this is clear enough to understand. As of right now, whenever I click the button, it always changes the number back to 0. That’s it. Just 0. No matter what I set the num var to, when clicking the mult button, it always reverts to 0.

Answer

You have to convert to number first.

multNum = parseInt(multNum);
number = number * multNum;
//...