Question

The problem I have is say I put 1 1/2, it would be 21/2 rather than 3/2. I know that it is thinking that this is a text string so it puts the text together rather than adding 2+1.

Please help! Here is my code:

    <head>
    <script>
    function convert(){

    var nu = Math.round(document.getElementById("nu"));
    var de = Math.round(document.getElementById("de"));
    var wh = Math.round(document.getElementById("wh"));

    var wdn = (wh.value*de.value)+nu.value;
    var display = document.getElementById("display");
    display.value = wdn+"/"+de.value;
    return false;
    }
    </script>
    </head>
    <body>
    <form onsubmit="return convert()">
    Whole: <input type="number" id="wh" style="width: 30px;">
    <br>
    <br>
    <input type="number" id="nu" style="width: 30px;">
    <br>
    --------
    <br>
    <input type="number" id="de" style="width: 30px;">
    <br>
    <textarea id="display" readonly style="border: 0px solid black; width: 300px; height: 200px;"></textarea>
    <br>
    <input type="submit" style="visibility: hidden;">
    </form>
    </body>
Was it helpful?

Solution

These lines of code need to be changed:

var nu = Math.round(document.getElementById("nu"));
var de = Math.round(document.getElementById("de"));
var wh = Math.round(document.getElementById("wh"));

var wdn = (wh.value*de.value)+nu.value;
var display = document.getElementById("display");
display.value = wdn+"/"+de.value;

Correct use:

var nu = Math.round(document.getElementById("nu").value);
var de = Math.round(document.getElementById("de").value);
var wh = Math.round(document.getElementById("wh").value);

var wdn = (wh*de)+nu;
var display = document.getElementById("display");
display.value = wdn+"/"+de;

Explanation:

Math.round() cannot work on the HTML element returned by document.getElementById(). However, it can work on the value contained in that element, which will convert the string to a number type (and also round it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top