简体   繁体   中英

Inserting dynamic option in the select tag, using Jquery

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'}) 
...

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

FIDDLE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM