Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decide the smallest even number from 2 input , correct it if the input number is not even. Any solution(Javascript/html)?

the code always thinks num1 is the smaller number ,even if it’s not + if the second input is odd, but the first is even, then the output is num1 the smaller even instead of "second input is odd, correct it"

+I would also need a "Both numbers are the same, correct it" output

this would be my wrong solution, how could I make it work?

function myFunction() {
    var num11, num2;
    num1 = Number(document.getElementById("num1").value);
    num2 = Number(document.getElementById("num2").value);

     if(num1%2==0 >num2%2==0){
        p2.innerHTML=num2+" is the smaller even number"
        if(num1%2!=0){
            p2.innerHTML=num1+" first input is odd, correct it"
        }
        else {
        p.innerHTML=num2+" second input is odd, correct it"
        }
     }
     else{
        p.innerHTML=num1+" is the smaller even number"
     }


}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is some updated code. I am not sure what your source code looks like so I’m basing it off my own minimum reproducible example.

I figured it would be easier to read if you split it up first by checking if both numbers are even. If they are not, check out which one is not even.

If they are even, you can just print the smaller one. I did it at the beginning for convenience but you can move it into the else statement if that’s preferred.

function myFunction() {
    var num11, num2;
    var p = document.getElementsByTagName("P")[0]
    num1 = Number(document.getElementById("num1").value);
    num2 = Number(document.getElementById("num2").value);
    
    var smaller = num1 < num2 ? num1 : num2

     if(num1%2!=0 || num2%2!=0){
        if(num1%2!=0){
            p.innerHTML=num1+" first input is not even, correct it"
        } else {
        p.innerHTML=num2+" second input is not even, correct it"
        }
     }
     else if (num1 === num2){
        p.innerHTML="Both numbers are equal, correct it."
     } else {
        p.innerHTML=smaller+" is the smaller even number"
     }


}
<p></p>

<input id="num1"/>
<input id="num2"/>

<button onclick="myFunction()">Run</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading