Selecting Text in a Field


field.setSelectionRange(0, field.value.length); 

Sometimes, text fields are prefilled with text explaining to the user what is expected in the field, for instance, in the following fashion:

<input type="text" name="textfield"   value="&lt;Enter data here&gt;" /> 


However, this is a bit cumbersome when users try to actually enter something in the field: They have to select the whole text to be able to overwrite the field's contents. If the text was preselected, this would be easy.

All major browsers support selecting text in a field; however, the approach is different. With Internet Explorer, the createTextRange() method of the field must be called, creating a range. The moveStart() and moveEnd() methods define the delimiters of this range; the select() method finally selects the text.

Mozilla browsers and Opera and Konqueror/KDE, on the other hand, have a different interface for this functionality. The setSelectionRange() method selects a field's contents. Note that setSelectionRange() expects the length of the range as second parameter, whereas moveEnd() in Internet Explorer expects the position of the last character to select.

The following listing selects the whole text in all major browsers and then sets the focus on the field. So if the user starts typing, the initial text is replaced immediately.

Preselecting Text in a Field (selecttext.html)

<script language="JavaScript"   type="text/javascript"> window.onload = function() {   var field = document.forms[0].elements["textfield"];   if (field.createTextRange) {     var range = field.createTextRange();     range.moveStart("character", .0);     range.moveEnd("character",       field.value.length - 1);     range.select();   } else if (field.setSelectionRange) {     field.setSelectionRange(0, field.value.length);   }   field.focus(); }; </script> <form>   <input type="text" name="textfield"     value="&lt;Enter data here&gt;" /> </form> 

Figure 8.6 shows the result. Note that when this form field is validated later, the default value should not be considered as valid data.

Figure 8.6. The text is selected, and the field has the focus.


Tip

You may consider prefilling the field only if JavaScript is available; otherwise, users without JavaScript would have to manually select (and delete) the standard value of the text field. The following code does the trick:

field.value = "<Enter data here>"; 






JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net