【问题标题】:JavaScript/jQuery – Add a character at the end of an input fieldJavaScript/jQuery – 在输入字段的末尾添加一个字符
【发布时间】:2012-06-01 18:50:47
【问题描述】:

我正在尝试创建一个输入字段,在输入时自动在输入的文本末尾放置一个问号。

我刚刚想出了这段代码,但显然它会生成多个问号。

$("#id").keyup(function(){
   $(this).val($(this).val() + "?");
});

感谢您的想法。

【问题讨论】:

  • 代码如何区分用户输入的问号和附加的脚本?换句话说,如果您在每个字符后都进行检查,您如何知道某人何时完成输入?

标签: javascript jquery input


【解决方案1】:
$("#id").keyup(function(){
    if ($(this).val().split('').pop() !== '?') {
        $(this).val($(this).val() + "?");
    }
});

DEMO

编辑:

(function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery));
$("#id").keyup(function(){
    if ($(this).val().split('').pop() !== '?') {
        $(this).val($(this).val() + "?");
        $(this).setCursorPosition( $(this).val().length - 1)
    }
});​

new DEMO

【讨论】:

  • @amnotiam 那你为什么要删除它?
  • 您的演示显示? 每隔一个字母放置。至少在 Firefox 中。
  • @amnotiam 这是因为光标位于? 之后,所以当您键入时,最后一个字母不再是?
  • 我认为这不是预期的结果。我很确定 OP 希望在他们键入时在最后保留一个问号。不过不确定。
  • 那么你需要一个cursor setting function also
【解决方案2】:
// Input is way better than keyup, although not cross-browser
// but a jquery plugin can add its support.
$('#id').on('input', function() {
    // If the last character isn't a question mark, add it
    if ( this.value[ this.value.length - 1 ] !== '?' ) {
        this.value += '?';
    }
});

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2010-10-23
    • 2017-06-22
    • 2023-01-09
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 2021-12-16
    相关资源
    最近更新 更多