How do I keep existing values from shifting to the right when entering keypresses into a jQuery Masked Input?

谁说我不能喝 提交于 2019-12-24 07:17:30

问题


I have a text box I'm using as a timer display "hh:mm:ss" When I select the box and press a number, it inserts the number at the cursor location, but instead of replacing the value at that position, it shifts all existing values over. For example, the timer text box reads "01:00:35" and I replace the first minute position with 1, the timer text box will then read "01:10:03."

Anybody know how to force the text box to replace, instead of insert, at the cursor position?

I've tried intercepting onKeyPress, doing the replace manually, rewriting the entire timer text, and then returning false. But, that doesn't worked with a jQuery masked input, because my function runs first.


回答1:


Looks like this is a feature of the masked input plugin. You can try modifying the plugin by replacing the following methods and then set the noshift option to true when you call the it(warning I did minimal testing on this, but it seemed to work) - $('#showTime').mask("99:99:99",{noshift:true});

    function shiftL(pos) {
      if(!settings.noshift){
        while (!tests[pos] && --pos >= 0);
        for (var i = pos; i < len; i++) {
          if (tests[i]) {
            buffer[i] = settings.placeholder;
            var j = seekNext(i);
            if (j < len && tests[i].test(buffer[j])) {
              buffer[i] = buffer[j];
            } else
              break;
          }
        }
      }
      writeBuffer();
      input.caret(Math.max(firstNonMaskPos, pos));
    };

    function keypressEvent(e) {
      if (ignore) {
        ignore = false;
        //Fixes Mac FF bug on backspace
        return (e.keyCode == 8) ? false : null;
      }
      e = e || window.event;
      var k = e.charCode || e.keyCode || e.which;
      var pos = $(this).caret();

      if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
        return true;
      } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
        var p = seekNext(pos.begin - 1);
        if (p < len) {
          var c = String.fromCharCode(k);
          if (tests[p].test(c)) {
            if(!settings.noshift) shiftR(p);
            buffer[p] = c;
            writeBuffer();
            var next = seekNext(p);
            $(this).caret(next);
            if (settings.completed && next == len)
              settings.completed.call(input);
          }
        }
      }
      return false;
    };


来源:https://stackoverflow.com/questions/2561252/how-do-i-keep-existing-values-from-shifting-to-the-right-when-entering-keypresse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!