Messed up option in select tag when value contains more than one word
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 "
:
htmlString += '<option value="' + branchesArray[i].branchName.replace(/"/g, '"') + '">' + 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>
精彩评论