'how to preserve space in HTML select option list<option value='hi this'>hi</option> [duplicate]

I have one select control. I try to update this control with jquery but the value after space omitting.

if (brandObj != "") {
    brandObj = eval("(" + brandObj + ")"); 
    $.each(brandObj, function(i, item) {
        $("#<%=listBrand.ClientID%>").append(  "<option value="+ item.Brand + ">" + item.Brand + "</option>");
    });

}

The data which I get from server

enter image description here

But after it render as HTML select , it omit the word after space.whole value is there but once I get the value , it have only half(the value which in double quote). I tried to add &nbsp; but it is showing as it is. it is not rendering as space. please give your suggession.

enter image description here



Solution 1:[1]

You should wrap value of attribute value in quote(Quote It). If you do not wrap them in quote then value after space will be considered as attribute itself:

$("#<%=listBrand.ClientID%>").append("<option value='"+ item.Brand + "'>" + item.Brand + "</option>");

Solution 2:[2]

As I've mentioned in the comment, the problem can be solved by wrapping the value attribute value in the quotes.

.append("<option value='" + item.Brand + "'>" ... 
                       ^                  ^

However, I'll recommend the use of Option constructor to create new <option> element dynamically.

Demo:

var arr = [{
    text: 'Hello World!',
    value: 'hello World'
}, {
    text: 'Bye World!',
    value: 'bye World'
}];

var select = document.getElementById('mySelect');

// Iterate over array
arr.forEach(function (obj, i) {
    // Create new <option> with dynamic value and text
    // Add the <option> to the <select>
    select.appendChild(new Option(obj.text, obj.value));
});
<select id="mySelect"></select>

Solution 3:[3]

Thanks to : Milind Anantwar, I adapted his idea and solved a problem that’s been nagging for about 5 days.

    <?php
    foreach($rows as $row):
        $outputstr="$row[Mfrname]";
        $goodstr="<option value='".$outputstr."''>".$outputstr."</option>";
        echo $goodstr;
    endforeach;
    ?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milind Anantwar
Solution 2 Community
Solution 3 RayH