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.
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]');
}