Reputation: 45
When I replace a string with another, the cursor is moved to the beginning of the string in the text. Can the cursor be moved at the end instead of the start of the string?
index.jsp:
var val1=request.responseText;
var text=document.getElementById("para").innerHTML;
if(val1!="true")
{
var afterplace=text.replace("good",val1);
document.getElementById("para").innerHTML=afterplace;
}
After replacement the cursor come at the start of the word I want it at the end.
Upvotes: 4
Views: 315
Reputation: 369
Use this code:-
var val1=request.responseText;
var text=document.getElementById("para").innerHTML;
if(val1!="true"){
var afterplace=text.replace("good",val1);
document.getElementById("para").innerHTML=afterplace;
document.getElementById("para").focus();
var val = document.getElementById("para").value;
document.getElementById("para").value = '';
document.getElementById("para").value = val;
}
It works fine for me.
Upvotes: 0
Reputation: 23826
Consider following function for setting cursor at end of contenteditable
element:
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
Full snippet:
var val1="testingtextgood";
var text=document.getElementById("para").innerHTML;
if(val1!="true")
{
var afterplace=text.replace("good",val1);
document.getElementById("para").innerHTML=afterplace;
document.getElementById("para").focus()
setEndOfContenteditable(document.getElementById("para"))
}
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
Upvotes: 1