Search code examples
javascriptstrip

Strip out 0 and any non number characters Javascript


How could I change this code to not allow a 0 and to strip out all non number characters?

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

Solution

  • EDIT: updated answer:

    you simply strip all the non non numbers then test if the number is not a 0 THEN you can perform your function.

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

    Hope this helps. Thanks Let me know if it does.

    PK