Accept comma in jquery / Javascript calculation

1

The system does not work when you type comma number, for example 2,14, 22,14 and etc ... only with end point 2.14, 22.14 and etc ... Below is the function I use. How to use function with the number typed with comma, do not present the error NaN and the result also appears with comma. Would it be possible to restrict the use of dot in the field or even issue an alert if the user types "."? Many thanks.

<script>
$(function(){
    $('.temp').change(function(){
        var total = 0;
        var notas = 0;
        $('.temp').each(function(){
            var nota = Number(this.value);
            if(nota === 0) return;
            total = total + nota;
            notas++;
        })
        var t = (total/notas).toFixed(2);
        $('#media_temperaturaE').val(t);
    });
})

Below the screen for entering numbers to perform the calculation, with both examples.

    
asked by anonymous 21.07.2016 / 20:52

1 answer

2

An alternative to your problem is to turn the ',' on '.' while the user types:

            $('input[type="text"]').keyup(function(){
                var val = $($(this)).val().replace(',','.');
                $($(this)).val(val);
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text" />

UPDATE See the logic above by performing a simple sum.

            $('input[type="text"]').keyup(function(){
                var val = $($(this)).val().replace(',','.');
                $($(this)).val(val);
                $('#result').val(Number($('input[name="number_01"]').val()) + Number($('input[name="number_02"]').val()));
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formaction="">
          <label for="">Number 01: </label><br>
          <input type="text" name="number_01" id="number_01"><br>
          <label for="">Number 02: </label><br>
          <input type="text" name="number_02" id="number_02"><br><br>
          <label for="">Result: </label><br>
          <input type="text" name="result" id="result">
        </form>

I hope I have helped.

    
21.07.2016 / 21:42