0

I'm modifying the data in a datetime input in JQuery in the Keyup event. If the date is 10/11/2000, but it's supposed to be 10/12/2000, after highlight the 11, and entering 12 (typing the 1 first), the cursor enters the 1, then jumps to the end of the data (after the 2000), and the data is then 10/1/2000 . I'd like the cursor to remain in the middle, after the 1 I just typed, so I can continue typing the 2. Any suggestions?

After every Keyup, and I am checking the data for formatting (mm/dd/yyyy) and setting it's correct format (mm/dd/yyyy). I think it's setting the value that is automatically moving the cursors.

I have tried, this.selectionStart and this.selectionRange, to no avail.

$('#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);
            
        });
scottydel
  • 13
  • 5

0 Answers0