(I m using html + J-query ) I have a situation in which I have a Text box ,and whenever the user types anything in it for the first time the character must be appended with @ symbol, and the next characters typed must be placed just before the @ symbol.
for ex.
when
1st char typed ‘c’ : c@
2nd char typed ‘f’ : cf@
3rd char typed ‘d’ : cfd@
This is what I have tried so far,
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
$("#myBox").on("keyup", function(){
var val = this.value;
if(!val.match(/@$/) && val.length>0){
this.value = val + "@"
}
setCaretPosition("myBox", this.value.length -1);
});