I needed to add as many options to dropdowns as there were dropdowns on my page. So I used it in this way:
function myAppender(obj, value, text){
obj.append($('<option></option>').val(value).html(text));
}
$(document).ready(function() {
var counter = 0;
var builder = 0;
// Get the number of dropdowns
$('[id*="ddlPosition_"]').each(function() {
counter++;
});
// Add the options for each dropdown
$('[id*="ddlPosition_"]').each(function() {
var myId = this.id.split('_')[1];
// Add each option in a loop for the specific dropdown we are on
for (var i=0; i<counter; i++) {
myAppender($('[id*="ddlPosition_'+myId+'"]'), i, i+1);
}
$('[id*="ddlPosition_'+myId+'"]').val(builder);
builder++;
});
});
This dynamically set up dropdowns with values like 1 to n, and automatically selected the value for the order that dropdown was in (i.e. 2nd dropdown got "2" in the box, etc.).
It was ridiculous that I could not use this or this.Object or $.obj or anything like that in my 2nd .each(), though --- I actually had to get the specific ID of that object and then grab and pass that whole object to my function before it would append. Fortunately the ID of my dropdown was separated by a "_" and I could grab it. I don't feel I should have had to, but it kept giving me jQuery exceptions otherwise. Something others struggling with what I was might enjoy knowing.
Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:
I needed to add as many options to dropdowns as there were dropdowns on my page. So I used it in this way:
This dynamically set up dropdowns with values like 1 to n, and automatically selected the value for the order that dropdown was in (i.e. 2nd dropdown got "2" in the box, etc.).
It was ridiculous that I could not use
this
orthis.Object
or$.obj
or anything like that in my 2nd.each()
, though --- I actually had to get the specific ID of that object and then grab and pass that whole object to my function before it would append. Fortunately the ID of my dropdown was separated by a "_" and I could grab it. I don't feel I should have had to, but it kept giving me jQuery exceptions otherwise. Something others struggling with what I was might enjoy knowing.using jquery you can use
where "myid" is the id of the dropdown list and newvalue is the text that you want to insert..
U can use direct
$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")
-> Here u can use direct string
Add item to list in the begining
Add item to list in the end
Common Dropdown operation (Get, Set, Add, Remove) using jQuery