如何在HTML中保留空格选择选项列表<option value =“hi this”> hi </option>

时间:2016-03-21 10:24:06

标签: javascript jquery html css asp.net

我有一个选择控件。我尝试使用jquery更新此控件,但是在省略空格后的值。

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

}

我从服务器获取的数据

enter image description here

但是在它呈现为HTML选择后,它会在space.whole值之后省略该单词但是一旦我得到该值,它只有一半(双引号中的值)。我试图添加&nbsp;,但它显示为原样。它不是渲染为空间。请给你的建议。

enter image description here

3 个答案:

答案 0 :(得分:10)

你应该在quote(Quote It)中包含属性值的值。如果你没有将它们包装在quote中,那么space之后的值将被视为属性本身:

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

答案 1 :(得分:4)

正如我在comment中提到的,可以通过在引号中包含value属性值来解决问题。

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

但是,我建议使用Option构造函数动态创建新的<option>元素。

<强>演示:

&#13;
&#13;
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));
});
&#13;
<select id="mySelect"></select>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

感谢:Milind Anantwar,我采纳了他的想法并解决了一个困扰了大约 5 天的问题。

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