Preserve whitespace in html select element options using “white-space: pre” NOT working

后端 未结 2 813
悲哀的现实
悲哀的现实 2020-12-20 14:05

My problem comes from HTML dropdown select not able to preserve multiple consecutive whitespaces in its options. Here is a sample testcase and outcome. The \"white-space:pre

2条回答
  •  不知归路
    2020-12-20 14:14

    The accepted answer is correct when dynamically creating the SELECT list from a server-side language. However, if you would like to create the options list in Javascript using the document.createElement function (probably the safest way to do so when using input you can't always completely control) then you can use the following method:

    var someSelectElement = document.getElementById("id_of_select_element");
    var optionSt = "Some spaces     go here.";
    var tObj = document.createElement("OPTION");
    
    tObj.value = 1; // whatever value you need.
    tObj.title = "Whatever title you want to appear when hovering over the option";
    
    tObj.text = decodeURI(optionSt.replace(/ /g, "%C2%A0")); // decodeURI is the key here.
    
    // Then add it to an already existing HTML select element...
    someSelectElement.appendChild(tObj);
    

提交回复
热议问题