Search code examples
javascripttype-conversionuser-input

weight conversion with user input javascript


i wrote a program which converts lbs to kg, it works fine. how would i ask the user to enter the conversion. for example, i have the weight set at 0.4536, but if i wanted it to be whatever the user wants how do i do that? i know in reality it would not change, but i'm thinking about future programs - possibly currency conversions where the rates change and i want the user to enter it easily.

Javascript

function onlyNumber(fld) {
     if(fld.value.match(/[^0-9.]/)) {
         fld.value=fld.value.replace(/[^0-9.]/g,'');
     }
}

function convertUnit(lbs, kilo) {
    retValue = 0;

    if (isNaN (kilo)) { alert ('Non-numeric value');  return 0; }
        kilo = parseFloat (kilo);
        var factor = 0.4536;

    if (lbs == 'kg2lb') {
         retValue = kilo/factor;
    }

    else if (lbs == 'lb2kg') {
         retValue = kilo*factor;
    }

    return retValue;
}

HTML

<form>
    <table>
        <tr>
            <td>LB<td>
            <input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
        </tr>
        <tr>
            <td>KG<td>
            <input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
        </tr>
    </table>
</form>

Solution

  • Add another input field or prompt the user.

    <form>
        <table>
            <tr>
                <td>LB<td>
                <input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
            </tr>
            <tr>
                <td>KG<td>
                <input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
            </tr>
            <tr>
                <td>Ratio<td>
                <input type="text" name="r" id="r" onkeyup="onlyNumber(this); window.ratio = this.value;">
            </tr>
        </table>
    </form>
    

    window.ratio = undefined;
    
    function convertUnit(lbs, kilo) {
        retValue = 0;
    
        if (isNaN (kilo)) { alert ('Non-numeric value');  return 0; }
            kilo = parseFloat (kilo);
    
        if (lbs == 'kg2lb') {
             retValue = kilo/window.ratio;
        }
    
        else if (lbs == 'lb2kg') {
             retValue = kilo*window.ratio;
        }
    
        return retValue;
    }
    

    Or with a prompt

    window.ratio = prompt("Which ratio to use ?"); // add validation