user2739179
user2739179

Reputation: 271

adding two different array value from select option in jquery (text & value)

how will i add another set of arrays and put it on the value of the option.

here is my dept array

var dept = ['dept1','dept2','dept3'];



$.each(dept, function(index, value){         
$("#filter2").append($("<option>",{
            value: value,  //--this is where i should put the value of array dept_id
            text: value
}));

i want to add my other array and put it inside the value of each option:

var dept_id = ['35', '36', '37'];

Upvotes: 3

Views: 338

Answers (3)

Riz
Riz

Reputation: 368

if you are aware of JSON you can have your data in this format following code snippet should help

var data = "[{'dep':'dept1','id':'35'},{'dep':'dept2','id':'36'},{'dep':'dept3','id':'37'}]";
data = JSON.parse(data);


$.each(data , function(index, value){         
$("#filter2").append($("<option>",{
        value: value.id,  //--this is where i should put the value of array dept_id
        text: value.dep
}));

Upvotes: 0

Man Programmer
Man Programmer

Reputation: 5356

insted of array you can use object method like this

var dept = {'35':'dept1','36':'dept2','37':'dept3'};

in each loop index return 35 and value return depart name

or if you want to use array then change like this

var dept = [];
dept[35] = 'dept1';
dept[36] = 'dept2';
dept[37] = 'dept3';

Upvotes: 0

fiddle Demo

use value: dept_id[index],

var dept = ['dept1', 'dept2', 'dept3'],
    dept_id = ['35', '36', '37'],
    filter2 = $("#filter2");
$.each(dept, function (index, value) {
    filter2.append($("<option>", {
        value: dept_id[index],
        text: value
    }));
});


Updated after OP's comment

fiddle Demo

var dept = ['dept1', 'dept2', 'dept3'],
    dept_id = ['35', '36', '37'],
    filter2 = $("#filter2");
$.each(dept_id, function (index, value) {
    filter2.append($("<option>", {
        value: value,
        text: 'dept' + ++index
    }));
});

Upvotes: 1

Related Questions