I’m building a string of HTML based on JSON data. In the HTML is a <select> with its <option>s. If the <option>‘s value is the same as some JSON data, it includes the selected="selected" attribute to the option tag as well. After that, the whole shebang is .append()ed to a display.
All of that seems to work fine and dandy, except that the selected option isn’t selected. Checking the code in Chrome’s Web Dev tools shows that the selected="selected" attribute is there. Doing a console.log() of the :selected options picks them up. However, when I drill down to a specific <option> and look at it, is shows the selected attribute as set to false.
Wha…?
I’ve tried using the .select() and .attr("selected","selected") jQuery methods after-the-fact to force the issue, but neither has made any difference.
Can anyone else figure out what’s going on here? It might just be my squirrely ignorance, but this seems to me like it should be working.
Code for reference. dataArray is an array of objects. $display is the jQuery wrapped <table> the HTML is .append()ing to:
$orderNumberField = jQuery("#orderNumber");
_orderNumberArray = $.parseJSON( $orderNumberField.val() );
for( n in dataArray ) {
var _displayString = "";
// ... other table data cells ...
_displayString += "<td><select class='orderNumSelect'>";
_displayString += " <option value=''></option>";
for( i in _orderNumberArray ){
_displayString += "<option value='" + _orderNumberArray[i] + "'";
if( dataArray[n].orderNum == _orderNumberArray[i] ) _displayString += " selected='selected'";
_displayString += ">" + _orderNumberArray[i] + "</option>";
}
_displayString += "</select></td>";
// ... still other table data cells ...
$display.append( _displayString );
}
I’m not sure what’s not working on your code,but you can try to generate the elements rather than appending text. I tested out with this code and it works fine