Just started learning JS need help / tips with code

Fred.

Well-known member
Hi,

I just started learing JS, I need to read 2 text fields and divide the largest nr. by the smallest and it may not be possible to divide by 0 (Has to show a alert) But negative numbers are allowed.

I think I started ok to make the objects and integers but I don't know how I have to divide and how I have to set all the parameters and else if...
Don't just post the solution please, try to explain me in a simple way what and how I have to do it. I'm trying to learn.

Thank you in advance. :)

This is the code I already have
Code:
<script>
// make objects
    var eGetal1 = document.getElementById('getal1');
    var eGetal2 = document.getElementById('getal2');
 
// make integers
    var nGetal1 = parseInt(eGetal1.value);
    var nGetal2 = parseInt(eGetal2.value);

// divide
    var nTotaal = "";
    if( nGetal1 > nGetal2 ) {
     What goes here???;
}
    if( nGetal2 > nGetal1 ) {
    What goes here???;
}

// alert not possible to divide by 0
var eKnop = document.getElementById('deKnop');
eKnop.onclick = sendAlert;
 
function sendAlert(){
     alert('inpossible to divide by 0');
}

//output
var eOutput = document.querySelector('#output');
eOutput.innerHTML = nTotaal;

console.log('getal1: ' + nGetal1);
console.log('getal2: ' + nGetal2);
console.log('totaal: ' + nTotaal);
</script>
 
Last edited:
Hint: division operator in JS is /

Code:
var oneHalf = 1 / 2; // equal to 0.5

For division by 0, you can either:

Code:
if (denominator == 0) {
    // alert goes here
}

Or compare the result directly:

Code:
if (numerator / denominator === Infinity) {
    // alert goes here
}

Your current code has:

Code:
 if( nGetal1 > nGetal2 ) {
   // What goes here???;
}


You said yourself "I need to read 2 text fields and divide the largest nr. by the smallest". Therefore you need to work out nGetal1 / nGetal2
 
Thanks @lol768
Well, I've been watching tutorials and seems to understand most things I learned so far. But everytime I come back to this my brain seems to stop. o_O

I don't understand in which order I have to do it and how.
I guess it goes like this. First check both integers find the largest and use that to divide by the other one. (no idea how to do this) if there is a 0 send an alert when they click the button. Also when they click the button it has to show the output.

I was able to let the alert pop-up but it always shows up, also if there is no 0.
I know the divide operator but how do I specify to divide the largest by the smallest?
I can say (nGetal1 / nGetal2) but what if nGetal2 is the largest? How do I do this. Do I have to do this with if else?

Thanks for you patience so far :D
I'm really trying to do my best to understand. :coffee: (PS : I was never good at math) :(
 
Last edited:
Top Bottom