Search code examples
htmlselectformattingtags

How put multiple spaces in an html SELECT tag?


I've got a web form and for the phone number entry, I'm listing three character countries and their calling codes inside a select tag like:

ARG +54
MOZ +258
USA +1

But I'd like to clean up its display so the calling codes are right justified and look like:

ARG  +54
MOZ +258
USA   +1

The longest dialing code is 5 characters so I was going to add spaces for the code length - 5. Spaces, of course, are compressed by the browser to one space. Same thing happens inside the SELECT. So, no problem, I'll just add enough   tags to make up the necessary number of spaces. But it displays:

ARG    +54

So, now the SELECT options are treated as text! Tried <pre>...</pre> in the options... showed the <pre>. Put <pre> outside the SELECT. Styled the SELECT with white-space:pre, pre-line, pre-wrap, normal, etc. and no joy.

I'd really like to know if there is a way to right justify the dialing codes within the select options.


Solution

  • I was able to achieve the result using a little code and the Unicode non-breaking space, \u00A0:

    var spaces = 6 - o.phonePrefix.length;
    var s = '\u00A0'.repeat(spaces) + o.phonePrefix;
    select.options[select.length] = new Option(o.code + s, o.phonePrefix); 
    

    And a little CSS, monospace and pre:

     <select style="font-family:monospace;white-space:pre;">
    

    Monospace ensures the characters are the same width and pre ensures spaces are preserved in the select.