使用用户输入javascript进行权重转换

weight conversion with user input javascript

本文关键字:权重 转换 javascript 用户 输入      更新时间:2023-10-27

我写了一个程序,可以将lbs转换为kg,效果很好。我该如何要求用户输入转换。例如,我将权重设置为0.4536,但如果我想让它成为用户想要的任何东西,我该怎么做?我知道事实上它不会改变,但我正在考虑未来的程序——可能是汇率变化的货币转换,我希望用户能够轻松输入。

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>

添加另一个输入字段或提示用户。

<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;
}

或者提示

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