简体   繁体   中英

Javascript event target value shows previous value of input box

I have a grid with multiple rows of input textboxes. I am trying to dynamically compute/show the current position and remaining character count for each row textbox (each can be 100 chars max)

$("#mygrid tbody").on('focusin', function(e) {
    if (e.target.tagName.toLowerCase() === 'input') {                
        let currentPosition = e.target.value.length === 0 ? 1 : e.target.value.length + 1;
        let remainingCharacters = 100 - e.target.value.length;
    }
});

$("#mygrid tbody").on('keydown', function(e) {
    if (e.target.tagName.toLowerCase() === 'input') {       
        console.log("e.target.selectionStart : " + e.target.selectionStart);
        console.log("e.target.value : " + e.target.value);
        let currentPosition = e.target.selectionStart + 1;
        let remainingCharacters = 100 - e.target.value.length;      
    }
});

What I am seeing is that there is a delay by 1 key shown by the console log statements ie as user types key-by-key "123", what gets logged is below;

e.target.selectionStart : 2
e.target.value : 12

I am confused why that might be happening?

To answer the specific question

event shows previous value of input box

I am confused why that might be happening

What is happening is: when a user presses a key the keydown event fires before the input has been updated - this allows you to cancel that key if it's not desired in your input.

If you had used keyup it would have fired after the input had been updated and your remainingCharacters code would have worked as expected.

As already suggested in another answer, using input is a good catchall and suitable for your scenario (so code not repeated here).

I wanted to explain why this was happening which was missing from the other solution.

Have a go with this. It makes more sense to use input than keydown/keypress etc

 $("#mygrid tbody input").on('input focus', function(e) { const val = this.value; let remainingCharacters = 100 - val.length; if (remainingCharacters <= 0) { remainingCharacters = 0; this.value = val.slice(0, 100) } $(this).next().val(0).toggleClass("red", remainingCharacters === 0) $(this).next().text(remainingCharacters) }).trigger("input");
 .red { color: red }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="mygrid"> <tbody> <tr> <td><input /><span>100</span></td> <td><input value="This is a test"/><span>100</span></td> <td><input /><span>100</span></td> </tr> <tr> <td><input /><span>100</span></td> <td><input /><span>100</span></td> <td><input /><span>100</span></td> </tr> </tbody> </table>

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