Reputation: 2538
I need to add a static text to textarea while typing.
var text= " my text";
$("#myInput").keydown(function() {
$("#myInput").val(this.value + text);
});
The above code adds " my text" to textarea, and after that if I continue typing, it starts to type after "text" word. I need my cursor stay always before " my text".
Upvotes: 2
Views: 978
Reputation: 3363
You need a function to get the cursor position:
Get cursor position (in characters) within a text Input field
And a function to set the cursor position:
jQuery Set Cursor Position in Text Area
Then you can do what you want:
var text= "my text";
var textIsSet = false;
$("#myInput").keydown(function() {
var cpos = doGetCaretPosition(this);
if(!textIsSet) {
$(this).val(this.value + text);
textIsSet = true;
}
setCaretToPos(this, cpos);
});
Here is a jsfiddle: http://jsfiddle.net/b69v5fvs/
Upvotes: 2
Reputation: 26360
With an input field or a textarea, it's dirty and doesn't work well (especially when deleting...)
var text= " my text";
$("#myInput").keyup(function() {
$(this).val(this.value.replace(text,"") + text);
});
input{
width : 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput"/>
I would rather use a contenteditable
element, with an :after
in pure CSS :
p{
min-width : 300px;
border: grey solid 1px;
}
p:after{
content:" my text"
}
<p contenteditable></p>
Upvotes: 1