I want to loop through my page and find every dropdown menu with a specific ID. I have no problem accessing the options collection of a dropdown but not the default selected value when the page first loads.
I have this dropdown which is in a loop:
@Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"), new {id = "ddlInterviewer" })
Here is my js which is in an external script:
$("#InterviewManagementFrm #ddlInterviewer > option").each(function () {
var lastChar = this.text.substr(this.text.length - 1);
if (lastChar == 'A') {
$(this).addClass("AcceptedPreference");
// this.text = this.text.slice(0, this.text.length - 1);
}
else if (lastChar == 'P') {
$(this).addClass("PreferredPreference");
// this.text = this.text.slice(0, this.text.length - 1);
}
});
I want to add a class to every dropdown item on the page. The addClass is used to stylize the dropdown item with a different color.
In my screenshot only unselected items have a color. That's because of the javascript adding the class. I want to add a class to the values that are selected by default on page load.
You can use the :selected
http://api.jquery.com/selected-selector/
$("#InterviewManagementFrm #ddlInterviewer > option").each(function () {
var lastChar = this.text.substr(this.text.length - 1);
if (lastChar == 'A') {
if( $(this).is(':selected') ) {
// add class
} else {
$(this).addClass("AcceptedPreference");
}
}
else if (lastChar == 'P') {
if( $(this).is(':selected') ) {
// add class
} else {
$(this).addClass("PreferredPreference");
}
}
});
You can also directly target the selected
$("#InterviewManagementFrm #ddlInterviewer > option:selected")
if #ddlInterviewer
is the id of the select then you don't need >
also ID should be unique
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.