Search code examples
javascriptjqueryonblur

jQuery blur behaving strangely


I want to listen blur event of every input field in the form, but when I reset the form after calculation, the again when i get focus of the input field it fires blur event two times, one with empty value and one with input value.

<form id="form">
    Total Ore to be Mined:
    <input type="number" name="TOmined" value="0" autofocus> Tons
    <br> Total Waste to be Mined:
    <input type="number" name="TWmined" value="0"> Tons
    <br> Number of Operating Days/Year:
    <input type="number" name="OperatingDays" value="0"> Days
    <br> Number of Operating Years:
    <input type="number" name="OperatingYrs" value="0"> Years
    <br>

</form>
<script>
    var arr = {};
    //  {"TOmined": inputValue}
    $(document).ready(function() {
        $(":input").blur(function(e) {
            var k = e.target.name;
            var v = e.target.value;
            arr[k] = v;
            console.log(k, v); // **runs two times one with empty string**
            // one with original value 

        })
    });

    function calculate() {
        var sum = 0;
        // your logic
        console.log(arr);

        // end logic
        if (!jQuery.isEmptyObject(arr)) {
            for (v in arr)
                sum += parseInt(arr[v]);
            console.log(sum);
        }
        $('#form').trigger("reset");
        //  $('#result').html(value to be displayed + ' tons/day');
        arr = {};
    }
</script>

Solution

  • Quickest way to spot the problem would be to add this line to your blur callback:

    console.log(e.target);
    

    ... which will show you the element that was blurred. In this case, it's your <button/> element that is triggering a blur event. You're binding the blur callback to all :input elements, and :input is a jQuery extension that includes input, textarea, select, and button elements (see documentation).

    To fix this, you'll just want to bind to real input elements, not the :input selector.

    $('input').blur(function (e) {
        // ...
    });