0

如何更改此代码以不允许 0 并删除所有非数字字符?

<script type="text/javascript">
    (function() {
        var a= document.getElementsByName('a')[0];
        var b= document.getElementsByName('b')[0];
        var c= document.getElementsByName('c')[0];

        a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
            c.value= Math.ceil((a.value/b.value)*100);
        };
    })();
</script>
4

2 回答 2

2

编辑:更新的答案:

您只需剥离所有非非数字然后测试数字是否不是 0 然后您可以执行您的功能。

   a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {

    // 1. First we will remove all non numbers from the values inputted by the user.
    var aValue = new String(a.value);
    var bValue = new String(b.value); 

    //Use regular expressions to strip out the non numbers incase the user types in non numbers.
    aValue = aValue.replace(/[^0-9]/g, '');
    bValue = bValue.replace(/[^0-9]/g, '');

    float newAValue = parseFloat("aValue"); 
    float newBValue = parseFloat("bValue"); 

    //2. Then test to see if the user has typed 0 as the value if they haven't then you an perform the maths.

    if((newAValue != 0) && (newBValue != 0))
        c.value= Math.ceil((av/bv)*100);
    };

希望这可以帮助。谢谢让我知道是否有。

PK

于 2010-10-01T14:04:05.377 回答
1
a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
  var av = parseFloat(a.value), bv = parseFloat(b.value);
  if(bv != 0)
    c.value= Math.ceil((av/bv)*100);
};
于 2010-10-01T13:54:48.493 回答