I got something to print but it is not the proper answer. Right now I am just getting "[object HTMLFormElement] is a Odd number"
no matter what number I enter weather it is even or odd.
function isEvenorOdd(num, form) {
if (num % 2 == 0) {
document.getElementById('result').innerHTML = `${num} is a Even number`
console.log(`${num} is a Even number`)
}
else {
document.getElementById('result').innerHTML = `${num} is a Odd number`
console.log(`${num} is a Odd number`)
}
}
Check if numbers are even or odd:
<form>
<input type="text">
<input type="button" value="Check"
onclick="isEvenorOdd (this.form);">
</form>
<div id="result"></div>
3
Answers
There are a few issues with your code
isEvenorOdd
function – you have two marametersnum
andform
. But when you call the function in theonclick
attr, you are only passing the form element (this.form
) not the input field.Here is a working example – fairly straight forward:
Big Int Example: for use case 11111111111111111 and 11111111111111112
As said, you are passing the form object and not the numeric value of the field. you need to get the text input, get its value, parse it to int, and then call
isEvenorOdd
:Instead of using an
onclick
function on your HTML it is much better to use eventListeners like this:Also if you are going to change the text of an element only then it is much better in terms of performance to use
textContent
thaninnerHTML
.Also you have to validate if the user actually typed numbers, since it’s an input text, they can type whatever they want, not necesarily a number so. If they type something like
Foo
then you have to validate withisNaN()
when you convert it to a number withNumber()
if that returnsNaN
then that means that he didn’t type a number so therefore it can’t be converted withNumber()
and you can return something like${num} is not a number