apex2022
apex2022

Reputation: 855

Retrieving number value from input instead of object

I am trying to write a small program to determine the common factors between two numbers. I am having a problem getting the numbers, though. Here is my HTML code:

<p>Please input two numbers to find the common factors between them.</p>
 First number:<input type="number" id="firstNumber"></br>
 Second number:<input type="number" id="secondNumber"></br>
<button onclick="commonFactors(document.getElementById('firstNumber'), 
 document.getElementById('secondNumber'))">Submit</button>

However, instead of getting the numbers back, the console returns the following:

"<input type='number' id='firstNumber'>" "<input type='number' 
  id='secondNumber'>"

With the quotes. Can you tell me what I'm doing wrong?

Not sure it matters, but here's the JS:

function commonFactors(num1, num2) {
  console.log(num1, num2);
  var counter=Math.min(num1, num2);
  var factors=[];
  var k=0;  
  for (i=1; i<counter; i++) {
    if (num1%i==0) {
      if (num2%i==0) {
        factors[k]=i;
      }
    }
    k+=1;
  }
}; 

Upvotes: 0

Views: 355

Answers (2)

Laassari
Laassari

Reputation: 326

because document.getElementById('firstNumber') is refering to the input, use +document.getElementById('firstNumber').value notice the + because the values you get from an input are of type string so we use the + to transform them to a number

Note: you can use a function instead of the + it's called parseInt() for integers and parseFloat() for float numbers

the result is

    <button onclick="commonFactors(parseInt(document.getElementById('firstNumber').value), 
 parseInt(document.getElementById('secondNumbe').value)">Submit</button>

Upvotes: 2

R Bayo
R Bayo

Reputation: 69

You want to get the value of the input, not the input itself :

document.getElementById('firstNumber').value

Upvotes: 1

Related Questions