Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Compare two numbers

    • 0
    • 0
    • 0
    • 2
    • 0
    • 0
    • 0
    • 805
    Answer it

    Can you tell me why this isn't working with comparing numbers?? All assistance is truly & greatly appreciated.

    function init(){ var a = document.getElementById("a").value; var b = document.getElementById("b").value; var compare = document.getElementById("comparison"); var submit = document.getElementById("submit");

    submit.onClick = function() {
        WhoWins(a,b);
    }
    
    function WhoWins(a, b) {
        if(a === b){
            displayResults = "=";
        }else if(a > b){
            displayResults = ">";
        }else if(a < b){
            displayResults = "<";
        }
    
    function displayResults() {
        output.innerHTML = compare;
    }
    
    }
    

    }

    window.onload = function(){ init(); }

 2 Answer(s)

  •  var a = document.getElementById("a").value

    As far as I understand, when you get a value you get a string but then you try to compare 2 strings (not numbers). So, if you want to get more correct comparison you need to cast your strings to integer:  a = Number(a);
  • Hi, You are passing value in displayResults function in a wrong way. Your code should be like this:

    var a = document.getElementById("a").value; 
    var b = document.getElementById("b").value; 
    var compare = document.getElementById("comparison"); 
    var submit = document.getElementById("submit");
    submit.onClick = function() {
    WhoWins(a,b);
    }
    function WhoWins(a, b) {
    if(a === b){
    displayResults ("=");
    }else if(a > b){
    displayResults (">");
    }else if(a < b){
    displayResults ("<");
    }
    function displayResults(result) {
    compare.innerHTML = result;
    }
    

    I hope it will give you expected result in field with compare id.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: