Phani Phani - 12 days ago 4x
jQuery Question

<option> value not being set

I have data returned by an ajax call, I am creating an option(dropdown select) element for each returned row of data, I need to make one of them default selected based on text. But value does not get assigned to the one I made "selected". Below is my code:

$.each(JSON.parse(r.d), function (key, value) {
if (value == 'Username') {
.append($('<option selected="selected">', { value: key })
else {
.append($('<option>', { value: key })

I am adding an option element for each returned row, and making the default selected one as "Username". When I look at the DOM after this has been added. I see this:

<option value="1">First Name</option>
<option value="2">Last Name</option>
<option selected="selected">Username</option>
<option value="4">Email</option>
<option value="8">Department</option>
<option value="9">Status</option>
<option value="10">Position</option>
<option value="11">Role</option>
<option value="12">User Group</option>
<option value="13">Course Code</option>
<option value="15">Enrollment Location</option>
<option value="16">Organization</option>

The option element with "Username" text does not have a value assigned, any idea why this is happening?


Set the selected attribute in the object as well, like this:

$('<option>', { value: key, selected: true })