1

I have an input on my HTML code, I want to change only a specific word in this input.

<input type="text" value="Input that I want to change only **this** word" id="inpWord">

when I keypress on this input, only change the word this, when I type/erease other word blocks me.

how can i do this on Jquery?

gFontaniva
  • 897
  • 11
  • 27

3 Answers3

1

I would suggest adding an event listener for the input event, which is fired synchronously when the value is changed (including when you paste a value in). If you want to strip out any optional whitespace around the desired word(s), you can replace /\s*this\s*/g with ' '.

var input = document.querySelector('input');

input.addEventListener('input', function(event) {
  this.value = this.value.replace(/\s*this\s*/g, ' ');
});
input { width: 100%; line-height: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" value="Input that I want to change only this word">

However, you will notice that there is an issue. The input caret will jump to the end of the field while you are typing because the entire value of the input element is being updated. To avoid this, you can implement this solution where the initial position of the caret is captured and then updated after the value is replaced:

var input = document.querySelector('input');

input.addEventListener('input', function(event) {
  var target = event.target;
  
  // Capture initial position
  var position = target.selectionStart;

  // This triggers the cursor to move.
  target.value = target.value.replace(/\s*this\s*/g, ' ');

  // Set the cursor back to the initial position.
  target.selectionEnd = position;
});
input { width: 100%; line-height: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" value="Input that I want to change only this word">
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0
$('#inpWord').on('keyup',function(){
  str = $(this).val().replace('this','that')
  $(this).val(str)
});
Nate Beers
  • 1,355
  • 2
  • 13
  • 22
0

I would use something like this. It will replace all the instances for you and its case insensitive. It will respond to change, keyup, and paste events. Try it out :-)

$('#replace').on('keyup paste change',function(){
  this.value = this.value.replace(/this/gi,'that');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="replace">
Lucas Shanley
  • 406
  • 2
  • 8