Reputation: 17439
I have writed this jquery code:
$(document).ready(function(){
$(document).on('change', '.prova > .target', function() {
$('div').removeClass('prova');
$(this).parent().after($('<br>'), $('<div>', {"class": 'prova'}).append(
$('<select>', {"class": 'target'}).append(
$('<option>', {value: 'option1', text: 'Option 1'}),
$('<option>', {value: 'option2', text: 'Option 2'})
),$('<input>', {type: 'number', style: 'width: 35px', min: '1', max: '99', value: '1'}),
$('<button>', {type: 'button' , "class": 'remove_item', text: 'delete' })));
});
});
The complete example here
The purpose of my code is the following:
Each time a new option is selected from the <select>
(only the last one) a new <select>
is created.
Now I want add, instead of the static option added from jquery code, a dynamic option. For example, supposing I have
var obj = {
"option1": "Option 1",
"option2": "Option 2"
};
How can I integrate in my jquery code the options listed above instead of the static insert:
...
$('<option>', {value: 'option1', text: 'Option 1'}),
$('<option>', {value: 'option2', text: 'Option 2'})
...
Upvotes: 1
Views: 1344
Reputation: 73966
You can do this:
var $mySelect = $('<select>', {
class: 'target'
});
$.each(obj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
Upvotes: 1