简体   繁体   中英

Last keyup event on delete not fired jquery

I have a strange behavior with the "keyup" event: When i fill out an input field with something, then i delete the value, the last delete keyup event isn't recognised.

Example code:

$('#input').on('keyup',function(){
 if($(this).val().length > 0){
    $('#text').html($(this).val())
 }
});

Fiddle HERE

Any solution or why this strange behavior?

Just change the comparator to >= instead of > and it works.

$('#input').on('keyup',function(){
    if($(this).val().length >= 0){
        $('#text').html($(this).val())
    }
});

Fiddle here

UPDATE

According to the new problem described in the fiddle the solution can be based on jQuery data :

 $(function () { $('#input-deposit').on('keyup', function (e) { if ($(this).val().length >= 0) { $('#text').html($(this).val()) } }); // set the default of previousValue $('#input-deposit').data('previousValue', 0); $('#input-deposit').on('keyup', function (e) { var t = 2000; if (!isNaN(this.value) && this.value.length != 0) { // get the previous value var previousValue = parseFloat($('#input-deposit').data('previousValue')); var total = parseFloat($('#input-balance').val()); var deposit = parseFloat($(this).val()); $('#input-deposit').data('previousValue', deposit); // use previousValue t = total + previousValue - deposit; } else { // reset previousValue $('#input-deposit').data('previousValue', 0); } $('#input-balance').val(t.toFixed(2)); }); }); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <label>Deposit</label> <input type="text" value="" id="input-deposit"/> <label>Balance</label> <input type="text" value="2000" id="input-balance"/> <div id="text"></div> 

The problem is:

if($(this).val().length > 0){

This must be:

if($(this).val().length >= 0){

Snippet:

 $(function () { $('#input').on('keyup',function(){ if($(this).val().length >= 0){ $('#text').html($(this).val()) } }); }); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <input type="text" value="" id="input"/> <div id="text"></div> 

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