JavaScript / jQuery - adding a character at the end of an input field

I am trying to create an input field that automatically places a question mark at the end of the entered text during input.

I just came up with this code, but obviously it generates a few question marks.

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

Thanks for your ideas.

+4
source share
2 answers
 $("#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

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

Source: https://habr.com/ru/post/1415642/


All Articles