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?
也设置对象中的selected
属性,如下所示:
$('<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
You can try something like this.
$.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 don't understand very much your code, but you are ask if value is Username I don't see a value like Username, because the value is missing in the dom maybe...
If your select id is ddlcriteria1 you can select the value to this form.
if (value == 'Username') {
$('#ddlcriteria1').val('Username');
}
it's all you need
If your code is good you can do this:
$.each(JSON.parse(r.d), function (key, value) {
if (value == 'Username') {
$('#ddlcriteria1').val('Username');
}
else {
$('#ddlcriteria1')
.append($('<option>', { value: key })
.text(value));
}
});
This is your code fixed :
$.each(JSON.parse(r.d), function (key, value) {
if (value == 'Username') {
$('#ddlcriteria1')
.append($('<option>', { value: key, selected: "selected" })
.text(value));
}
else {
$('#ddlcriteria1')
.append($('<option>', { value: key })
.text(value));
}
});
You should set the selected
attribute in the array in the second parameter of the append
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.