0

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;
  }
}; 

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to both of you! It took a combination of both parseInt and .value to work.
yeah, you'll need both of them as stated in the first paragraph. I forgot to add .value in the example
1

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

document.getElementById('firstNumber').value

1 Comment

Thanks! See above comment.

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.