简体   繁体   中英

Browser not displaying spaces of list text within SELECT tag?

I am using IE7 and it seems to display options in my SELECT tag without the leading spaces in the text - the text seems to be trimmed. For example, in the HTML code block below, even though option 1 to 3 have three spaces in the front of its text, the browser when displaying them seems to perform a trim and displays it to the user without the leading spaces.

Code block 1:

<select size="3">
    <option value="1">   aaa</option>
    <option value="2">   bbb</option>
    <option value="3">   ccc</option>
    <option value="4">ddd</option>
    <option value="5">eee</option>
</select>

It also seems that when you access the option's text through JavaScript, the returned value is also trimmed.

Code block 2:

var value = list.options[i].text;

Is there a way to force the browser to display the spaces as well or is this something I am stuck with?

Use &nbsp; instead of spaces:

<select size="3">
    <option value="1">&nbsp;&nbsp;&nbsp;aaa</option>
    <option value="2">&nbsp;&nbsp;&nbsp;bbb</option>
    <option value="3">&nbsp;&nbsp;&nbsp;ccc</option>
    <option value="4">ddd</option>
    <option value="5">eee</option>
</select>

=== UPDATE ===
Also see my jsfiddle .

Did you try

&nbsp; 

in lieu of a space?

Not sure but try having &nbsp ; instead of just a space

It's browser behavior, removing white space from the option text.. I found out that the innerHTML is "preserved" though, so you can keep the HTML intact with the ordinary spaces then just add this JS:

window.onload = function() {
    var dropDownLists = document.getElementsByTagName("select");
    for (var i = 0; i < dropDownLists.length; i++) {
        var oDDL = dropDownLists[i];
        for (var j = 0; j < oDDL.options.length; j++) {
            oDDL.options[j].innerHTML = oDDL.options[j].innerHTML.replace(/ /g, "&nbsp;");
        }
    }
};

This will replace the space with its HTML entity for you.

Live test case .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM