Reputation: 421
I'm not sure how simple or how complicated this question may as I am just learning javascript, but here it goes.
Say I have an input field:
<input type="text" value=""/>
I am trying to write a javascript function that checks the input value every time a space is entered, and then edit the value live while the user is typing.
For example, say I start typing: hello, how are u
After I hit space following 'u', I would like to replace 'u' with 'you'.
So, if anyone who be so kind, where do I start here? This may be ironic because I see the text I am typing right this instant being updated just to the bottom of this textarea. However, I am trying to get it to update in the field itself.
Thanks!!!
Upvotes: 3
Views: 6270
Reputation: 16369
You don't necessarily need jQuery to do this, but it is a little more work with vanilla JS. First, give your input an ID:
<input id="ValueField" type="text" value="" />
Then add an event listener:
var field = document.getElementById('ValueField');
field.addEventListener('keyup',function(e){
if(e.keyCode==32){
// do your stuff
}
});
There are a million ways to detect change, but first thing that comes to mind is a function:
var field = document.getElementById('ValueField');
field.addEventListener('keyup',function(e){
if(e.keyCode==32){
field.value = replaceValues(field.value);
}
});
function replaceValues(fieldval){
var baditems = [' u ',' i '],
newitems = [' you ',' I '],
length = baditems.length;
for(var i = length; i--;){
fieldval = fieldval.replace(baditems[i],newitems[i]);
}
return fieldval;
}
Just build out the array of bad and new items to be the same length with their order matching and you should be good. This way you can replace as many items you want, and should run pretty quickly.
EDIT
Might help if I have the function return something! Here is a jsFiddle to show example. Also, I had to add spaces around the u
and i
because otherwise it would just match any instance of the letter.
Upvotes: 1
Reputation: 8599
if you are using jquery, look at this: https://stackoverflow.com/a/2249215/146602
good way to detect if a space character is being used.
Upvotes: 0