JavaScript / jQuery - 在输入字段的末尾添加一个字符

时间:2012-06-01 18:50:47

标签: javascript jquery input

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

我刚刚想出了这段代码,但很明显它产生了多个问号。

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

感谢您的想法。

2 个答案:

答案 0 :(得分:7)

$("#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

答案 1 :(得分:0)

// 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 += '?';
    }
});