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') {
$('#ddlcriteria1')
.append($('<option selected="selected">', { value: key })
.text(value));
}
else {
$('#ddlcriteria1')
.append($('<option>', { value: key })
.text(value));
}
});
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 })
Make it good:
var optionElement = $('<option/>').attr({
"selected":"selected",
"value": key
});
$('#ddlcriteria1')
.append(optionElement)
.text(value));
With your code you are overriding the last properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With