Reputation: 63
I've got a bit of a tricky issue. I'm trying to add a third parameter to the following function/loop and have hit a wall. Help?
$.each(studentselectValues, function(key, value) {
$('select[name="cf_Student"]')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
Here's what the code looks like for the studentselectValues
variable:
studentselectValues = {
'1': 'My 1st Option',
'2': 'My 2nd Option',
'3': 'My 3rd Option'
}
What I'm doing is populating a select with the options shown above. My goal is to add a third attribute to each select. Does anyone have a clue how I would accomplish this?
Thanks in advance.
Upvotes: 0
Views: 193
Reputation: 17984
studentselectValues = [{
{key:'1', value:'My 1st Option', third:"third value"},
{key:'2', value:'My 2nd Option', third:"third value"},
{key:'3', value:'My 3rd Option', third:"third value"}
}];
$.each(studentselectValues, function(index, data) {
$('select[name="cf_Student"]')
.append($("<option></option>")
.attr("value",data.key)
.text(data.value+ " "+ data.third));
}
On a sidenote, you shouldn't append each item in the loop: it's resource-heavy. Concatenate and then append instead.
var studentselectValues = [{
value: '1',
key: 'test',
third: 'hoho'
}, {
value: '2',
key: 'test2',
third: 'test'
}];
var options = [];
$.each(studentselectValues, function () {
options.push('<option value="' + this.key + '">' + this.value + ' ' + this.third + '</option>');
});
var optionsS = options.join();
$('select[name="cf_Student"]').append(optionsS);
Upvotes: -1
Reputation: 135
I recomend you to make a array with objects, then are you possible to feed it with what you want.
var studentselectValues = [
{ value: 1, label: 'test', extraattr: 'hoho' },
{ value: 2, label: 'test2', extraattr: 'test' }
];
$.each(studentselectValues, function() {
$('select[name="cf_Student"]')
.append($("<option/>")
.val(this.value)
.attr('data-id', this.extraattr)
.text(this.label));
});
Upvotes: 0
Reputation: 102793
I'd make the studentselectValues
hash into an array of hashes ... that way you can use as many attributes as you need:
studentselectValues = [
{ id: '1', key: 'My 1st Option', text: 'First' },
{ id: '2', key: 'My 2nd Option', text: 'Second' },
];
$.each(studentselectValues, function(index, item) {
$('select[name="cf_Student"]')
.append($("<option></option>")
.attr("value",item.key)
.text(item.text));
});
Upvotes: 5