Replace char OnKeyPress
Asked Answered
G

5

11

I have a textarea input element,

If the user types "@" I want to replace it with @[someTextHere].

I'm using JQuery's keypress event, but I havent been able to get what I want, I keep getting the "@" at the end of the string , I.e. [someTextHere]@.

Is it possible?

My Code:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    </head>

    <body>
        <textarea id="post-txt"></textarea>
    </body>
</html>

<script>
    $('#post-txt').keypress(function(event){
        var str = $('#post-txt').val(); 

        if(String.fromCharCode(event.which) == '@'){
            $('#post-txt').val(str.substring(0,str.length) + '[TEXT]'); 
            }
    })  
</script>

Assistance would be appreciated.

Guyguyana answered 7/5, 2015 at 10:15 Comment(3)
Why not just say: $('#post-txt').val(str + '[TEXT]');Rettarettig
@Tsalikidis Your solution doesn't work.Guyguyana
I didn't claim it's a solution... I just asked why make it complicated using substring..Rettarettig
W
5

that's because he adds the character after the execution of the function.you can prevent the addition of the character and add it in your code.

 if(String.fromCharCode(event.which) == '@'){
    event.preventDefault()
    $('#post-txt').val(str + '@[TEXT]'); 
 }
Which answered 7/5, 2015 at 10:21 Comment(0)
D
2

Here is a wonderful solution from kristofdegrave which takes into account selection and the cursor position.

var replacedChar = '@';
var replacement = '@[SomeTextHere]'
var moveCursorBy = replacement.length - replacedChar.length; //Or 0 if you want the cursor to be after between '@' and '[SomeTextHere]'

$('textarea').keypress(function(e){
  if(e.key == replacedChar){
    // IE
    if(document.selection){
      // Determines the selected text. If no text selected, the location of the cursor in the text is returned
      var range = document.selection.createRange();
      // Place the replacement on the location of the selection, and remove the data in the selection
      range.text = replacement;
      // Chrome + FF
    } else if(this.selectionStart || this.selectionStart == '0') {
      // Determines the start and end of the selection.
      // If no text selected, they are the same and the location of the cursor in the text is returned
      // Don't make it a jQuery obj, because selectionStart and selectionEnd isn't known.
      var start = this.selectionStart;
      var end = this.selectionEnd;
      // Place the replacement on the location of the selection, and remove the data in the selection
      $(this).val($(this).val().substring(0, start) + replacement +                       $(this).val().substring(end, $(this).val().length));
      // Set the cursor back at the correct location in the text
      this.selectionStart = start + moveCursorBy + 1;
      this.selectionEnd = start + moveCursorBy + 1;
    } else {
      // if no selection could be determined,
      // place the replacement at the end.
      $(this).val($(this).val() + replacement);
    }
    return false;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea></textarea>
Demarcate answered 8/6, 2018 at 14:47 Comment(0)
A
0

I took the liberty to make a jquery function out of the function posted by Alexandru Severin:

$.fn.replaceCharOnKeyPress = function(chr, replacement) {
    var moveCursorBy = replacement.length - chr.length;
    this.each(function() {
        $(this).keypress(function(e) {
            if (e.key == chr) {
                // IE
                if(document.selection) {
                    // Determines the selected text. If no text selected, the location of the cursor in the text is returned
                    var range = document.selection.createRange();
                    // Place the replacement on the location of the selection, and remove the data in the selection
                    range.text = replacement;
                }
                // Chrome + FF
                else if(this.selectionStart || this.selectionStart == '0') {
                    // Determines the start and end of the selection.
                    // If no text selected, they are the same and the location of the cursor in the text is returned
                    // Don't make it a jQuery obj, because selectionStart and selectionEnd isn't known.
                    var start = this.selectionStart;
                    var end = this.selectionEnd;
                    // Place the replacement on the location of the selection, and remove the data in the selection
                    $(this).val($(this).val().substring(0, start) + replacement + $(this).val().substring(end, $(this).val().length));
                    // Set the cursor back at the correct location in the text
                    this.selectionStart = start + moveCursorBy + 1;
                    this.selectionEnd = start + moveCursorBy + 1;
                }
                else {
                    // if no selection could be determined,
                    // place the replacement at the end.
                    $(this).val($(this).val() + replacement);
                }
                return false;
            }
        });
    });
    return this;
};

Usage example:

$(form).find('input.price').replaceCharOnKeyPress(',', '.');
Adolpho answered 16/11, 2018 at 12:38 Comment(0)
N
0

Live demo

<script type="text/javascript">
$("#input").on('input keydown paste', function() {
  $(this).val($(this).val().replace(/@(?![[])/g, '@[some text]'));
  var key = event.keyCode || event.charCode;
  if (key == 8 || key == 46) {
    this.select();
  }
});
</script>

This regex **/@(?![[])/g** makes sure that only a single @ is matched not @[ there by running the code only once.

This code also makes sure that even if the user pasted the @ symbol they will get @[some text] in the input box.
 
this.select() makes sure that @ will not fire again when the user tries to delete with either the backspace or delete button (when you delete '[' from '@[' the regex is no longer able to differentiate, therefore the code fires @[some text] again this is what this.select() prevents by selecting the entire @[some text] and removing it in on swoop).

Any Questions leave a comment below!
Nonexistence answered 12/5, 2021 at 22:19 Comment(0)
H
-1
$(document).find('input').keypress(function(evt){ 
        if(evt.which==50){
            $(this).val($(this).val()+'[Letter to replace]');
            evt.preventDefault();
        }
    });

Try this...

Haff answered 7/5, 2015 at 10:37 Comment(1)
If the cursor is not in the last position in the input box this solution won't work correctly as only adds the [Letter to replace] at the end.Moonshiner

© 2022 - 2024 — McMap. All rights reserved.