moving the cursor to the end of a textboxes text

M

mr_burns

Hi there,

I am using the following code to enter text into text box when it is
empty:

<input name="txt_url" type="text" class="form_text_300" id="txt_url"
onClick="if(this.value == ''){this.value = 'http://';}">

it works fine but when it enters the text - 'http://' - the cursor
jumps back to the start of the line in the text box. How do I then
make the cursor be placed at the end of the text. For example:

http://
here------------------'

http://
and not-------'

Cheers

Burnsy
 
D

Daniel Kirsch

mr_burns said:
How do I then
make the cursor be placed at the end of the text.

Some helpfull functions:

function setSelectedTextRange(elm, selectionStart, selectionEnd) {
if (elm.setSelectionRange) {
elm.focus();
elm.setSelectionRange(selectionStart, selectionEnd);
}
else if (elm.createTextRange) {
var range = elm.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToEnd (elm) {
setSelectedTextRange(elm, elm.value.length, elm.value.length);
}
function setCaretToStart (elm) {
setSelectedTextRange(elm, 0, 0);
}
function setCaretToPos (elm, pos) {
setSelectedTextRange(elm, pos, pos);
}


Use it like this:
var iField = document.getElementById("inputfield");
iField.value = "foobar";
setCaretToPos(iField,3);
//or
setCaretToEnd(iField);

Or in your case:
<input name="txt_url" type="text" class="form_text_300" id="txt_url"
onClick="if(this.value == ''){this.value = 'http://';setCaretToEnd(this);}">

Daniel
 
J

Julian Turner

Hi there,

I am using the following code to enter text into text box when it is
empty:

<input name="txt_url" type="text" class="form_text_300" id="txt_url"
onClick="if(this.value == ''){this.value = 'http://';}">

it works fine but when it enters the text - 'http://' - the cursor
jumps back to the start of the line in the text box. How do I then
make the cursor be placed at the end of the text. For example:

http://
here------------------'

http://
and not-------'

Cheers

Burnsy

Try:-

IE

var rRange=document.body.createTextRange();
rRange.moveToElementText("txt_url");
rRange.collapse(false);
rRange.select();

Mozilla

var nLength=txt_url.value.length;
txt_url.focus();
txt_url.setSelectionRange(nLength,nLength);


Julian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top