Try setting the value of the select after creating it:
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
select.val('@Model.ID');
سؤال
i have the following jQuery code inside my razor view:-
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
which populate a drop down list. but how i can check if the current itemData.Value equals certain Model value , and select its value if so. somthing such as :-
if(itemData.Value == @Model.ID).attr('selected', true);
Thanks
المحلول
Try setting the value of the select after creating it:
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
select.val('@Model.ID');
نصائح أخرى
You can do this stuff after the dropdown-list bound,
if(itemData.Value == @Model.ID)
{
$("#dropdownID option[value='" + itemData.value +"']").attr("selected","selected"); // .prop('selected','selected')
}
This way your function should look like this:
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
if(itemData.Value == @Model.ID)
{
$("#dropdownID option[value='" + itemData.Value +"']").attr("selected","selected"); // .prop('selected','selected')
}
});
How about:
if(itemData.Value == @Html.Raw(Model.ID)).attr('selected', true);
or put quotes around it if needed:
if(itemData.Value == @Html.Raw("'" + Model.ID + "'")).attr('selected', true);
// let's assume the following data
var CSData = {
"itemA": "foo a",
"itemB": "foo b",
"itemC": "foo c"
};
// let's assume this as the select element
var select = $("#fooData");
// let's append the CSData to the select
$.each(CSData, function (index, itemData) {
// first solve how you append the select element
select
.append($("<option></option>")
.attr("value", index)
.text(itemData));
if(itemData.Value == @Model.ID){
// matched, do whatever here
}
});