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.

1
  • 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? Commented Jun 1, 2012 at 19:02

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

@amnotiam So why did you delete it?
Your demo shows that a ? is placed every other letter. At least in Firefox.
@amnotiam that's because the cursor is placed after the ? so then when you type, the last letter isn't a ? anymore.
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.
So then you need a cursor setting function also
|
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 += '?';
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.