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

Viewed 227

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.

3 Answers

You have to convert to number first.

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

First of all, the obvious: Multiplying any number with your number variable which has 0 value will lead to 0 at all times - I suppose you know this but was confused or missed that part, probably by confusing it to initialization of 0 before an addition process. Set it to 1 or another non-negative number and you will probably get better results on the way. :)

In addition, to make it multiply correctly in JS, you have to multiply between two numbers. Your value is of type String as inserted in your input field. As already suggested by @Si8, you need to parse it to Number by doing:

multNum = parseInt(multNum);

Also, you seem to be using a text type for your input. I suggest you set it to a number type, so that you restrict input values:

<input type="number" id="multNumInput">

Check out the Mozilla MDN web docs for more on this.

The answer, as provided by @Robin Zigmond in a comment is this:

"You're failing to convert multNum from a string to a number."

Related