5

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • How would the code differentiate a question mark the user entered from one the script appended? In other words, how would you know when someone is done typing if you're checking after every character? – j08691 Jun 01 '12 at 19:02

2 Answers2

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

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • @amnotiam So why did you delete it? – qwertymk Jun 01 '12 at 18:58
  • Your demo shows that a `?` is placed every other letter. At least in Firefox. –  Jun 01 '12 at 18:58
  • @amnotiam that's because the cursor is placed after the `?` so then when you type, the last letter isn't a `?` anymore. – qwertymk Jun 01 '12 at 18:59
  • I don't think that's the desired outcome. I'm pretty sure OP wants to maintain a question mark at the end as they type. Not sure though. –  Jun 01 '12 at 19:00
  • So then you need a [**cursor setting function also**](http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area) – qwertymk Jun 01 '12 at 19:01
  • Yes, am not i am, that's what i was trying to do but failed. –  Jun 01 '12 at 19:02
  • comments on the code would be nice, thanks either way for posting –  Jul 19 '15 at 07:39
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 += '?';
    }
});
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116