简体   繁体   中英

blur event not working as expected with dynamically created inputs

I have a table which can have some dinamically created inputs, so the user can throw in some values and make some calculations:

<table>
   <thead>...</thead>
   <tbody>
     <tr>
        <td>Info</td>
        <td><input class="inputsTable"/></td>
        <td><input class="inputsTable"/></td>
   </tbody>
</table>

When the user inputs a value and the blur event occurs, the system would do some calculations. I had the "multiple blur events firing" problem and i solved like this:

<script>
    $(document).ready(function () {        
        $(".inputsTable").mask("#.##0,00", { reverse: true });
        //setting up masks
    });

    let isBound = false;
    $('.inputsTable').on('input propertychange paste', function () {
        if (!isBound) {
            isBound = true;
            $(this).on('blur', function () {
                alert($(this).val());
            });
        }
    });

</script>

It works for the first input. If i try to fire the blur event from the second input, it won't work. And if i reset the isBound variable:

$('.inputsTable').on('input propertychange paste', function () {
            if (!isBound) {
                isBound = true;
                $(this).on('blur', function () {
                    alert($(this).val());
                    isBound = false;
                });
            }
        });

Sometimes it works, but sometimes it will fire multiple times. How can i solve this?

Try this if it works. If you are inserting or appending inputs dynamic then you should use document to reload the DOM.

 $(document).on('.inputsTable','input propertychange paste', function () {
        if (!isBound) {
            isBound = true;
            $(this).on('blur', function () {
                alert($(this).val());
                isBound = false;
            });
        }
    });

OR

 $(document).on('.inputsTable','input propertychange paste', function () {
         $(this).on('blur', function () {
            alert($(this).val());
         });
    });

But it would be fine if you upload the full code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM