简体   繁体   中英

JavaScript/jQuery – Add a character at the end of an input field

I'm trying to make an input field which automatically puts a questionmark at the end of the typed text while typing.

I just came up with this code but obviously it generates multiple questionmarks.

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

Thank you for your ideas.

$("#id").keyup(function(){
    if ($(this).val().split('').pop() !== '?') {
        $(this).val($(this).val() + "?");
    }
});

DEMO

EDIT:

(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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM