faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

95 of 114 people (83%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can I right align text in a text field?

Apr 27th, 2001 07:11
mark M, Luiz Paulo Rosa, Martin Honnen,


IE4/5 support style settings on this in the form of
  <FORM NAME="aForm">
  <INPUT TYPE="text" NAME="aField" STYLE="text-align: right;">
  </FORM>
Unfortunately NN4 with this style settings right-aligns the whole text 
field which is hardly what you want. So better document.write such a 
field:
  <FORM NAME="aForm">
  <SCRIPT>
  if (document.all)
    document.write('<INPUT TYPE="text" NAME="aField" SIZE="10" 
STYLE="text-align: right;">')
  else
    document.write('<INPUT TYPE="text" STYLE="font-family: Courier 
New;" NAME="aField" SIZE="10" ONCHANGE="rightAlign(this, 10)">');
  </SCRIPT>
  </FORM>
The code to right align onchange works with IE too if a non 
proportional font is choosen so
  <FORM NAME="aForm">
  <INPUT TYPE="text" STYLE="font-family: Courier New;" NAME="aField" 
SIZE="10" ONCHANGE="rightAlign(this, 10)">
  </FORM>
will also do with both browsers.
The function used is
<SCRIPT>
function rightAlign (field, size) {
  size = field.size ? field.size : size ? size : 20;
  var v = field.value;
  while (v.length < size)
    v = ' ' + v;
  field.value = v;
}
</SCRIPT>
....this will cause a problem, however, if you have the maxlength 
property set.