开发者

Messed up option in select tag when value contains more than one word

开发者 https://www.devze.com 2023-04-13 09:59 出处:网络
I\'m building a drop-down menu this way: var htmlString = \'<select id=\"sAddress\">\'; for (var i=0; i<branchesArray.length; i++){

I'm building a drop-down menu this way:

var htmlString = '<select id="sAddress">';

for (var i=0; i<branchesArray.length; i++){     
    htmlString += '<option value=' + branchesArray[i].branchName + '>' + branc开发者_如何学PythonhesArray[i].branchName + '</option>';
}
htmlString += '</select>';
$('.shopAddress').append(htmlString);

Now, the problem is that if branchesArray[i].branchName contains one word than it's OK, but if it contains two words separated by space, than instead of getting this:

<option value="West Coast">West Coast</option>

I'm getting this:

<option Coast="" value="West">West Coast</option>

How can I solve this?


You have to use quotes when the value of an attribute contains whitespaces. If there's possibility that your string contains a double quote, you have to replace it (see second example):

htmlString += '<option value="' + branchesArray[i].branchName + '">' + branchesArray[i].branchName + '</option>'

Replacing double quotes by HTML entity &quot;:

htmlString += '<option value="' + branchesArray[i].branchName.replace(/"/g, '&quot;') + '">' + branchesArray[i].branchName + '</option>'

Currently, your generated HTML looks like:

<option value=West Coast>West Coast</option>  which is interpreted as:
<option value="West" Coast>West Coast</option> (attributes: value=west, Coast="")
<option value="West" Coast="">West Coast</option>
0

精彩评论

暂无评论...
验证码 换一张
取 消