如何在 JQuery 的 Keyup 事件中保留光标位置?

问题描述 投票:0回答:0

我在 Keyup 事件中修改 JQuery 中日期时间输入的数据。如果日期是10/11/2000,但应该是10/12/2000,高亮显示11后,输入12(先输入1),光标输入1,然后跳到数据末尾(2000 年之后),然后数据为 10/1/2000 。我希望光标保持在中间,在我刚刚输入的 1 之后,这样我就可以继续输入 2。有什么建议吗?

每次 Keyup 之后,我都会检查数据的格式 (mm/dd/yyyy) 并设置正确的格式 (mm/dd/yyyy)。我认为它正在设置自动移动光标的值。

我试过了,

this.selectionStart
this.selectionRange
,都无济于事。

$('#DateOfBirth').keyup(function (e) {

            var dob = this.value.replace(/\D/g, '').substring(0, 8);

            // Backspace and Delete keys
            var deleteKey = (e.keyCode == 8 || e.keyCode == 46);

            var len = dob.length;

            //Modify to mm/dd/yyyy format

            if (len == 0) {
                dob = dob;
            } else if (len < 2) {

                dob = dob;
            } else if (len == 2) {
                if (dob > 12) { dob = 12; }
                dob = dob + (deleteKey ? '' : '/');
            } else if (len < 4) {
                dob = dob.substring(0, 2) + '/' + dob.substring(2, 4);
            } else if (len == 4) {
                dob = dob.substring(0, 2) + '/' + dob.substring(2, 4) + (deleteKey ? '' : '/');
            } else {
                dob = dob.substring(0, 2) + '/' + dob.substring(2, 4) + '/' + dob.substring(4, 8);
                //alert(dob.substring(0, 2) + " " + dob.substring(2, 4) + " " + dob.substring(4, 8));
            }
            this.value = dob; <-- removing this line, the cursor remains in the same position an edit

            //attemped some things here but nothing helped
            //this.selectionStart = this.selectionEnd = this.value.length;
            //this.setSelectionRange(cursorStartPosition);
            
        });
jquery date input cursor keyup
© www.soinside.com 2019 - 2024. All rights reserved.