0

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.

3 Answers 3

5

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)); 
});

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

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));
  });

Comments

-1
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.