How to add dynamically a combobox using jQuery

后端 未结 2 1394
孤独总比滥情好
孤独总比滥情好 2021-01-20 04:39

I\'ve this working code which is creating one combobox:

You can see it working here: jsfiddle

$(\'body\').on(\'chan         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 04:58

    I'm not entirely sure if your intent, but it seems like you want to have groups of two select elements and then adding a new group when the user selects a value.

    In that case I suggest grouping your two selects in a fieldset like this:

    ​ And then looking up that parent fieldset and cloning it like this:

    $('body').on('change', '.combo', function() {
      var selectedValue = $(this).val();
    
      var fieldset = $(this).parents('fieldset');
    
      if ($(this).find('option').size() > 2) {
        var newFieldset = fieldset.clone();
        var newComboBox = $(fieldset).children('.combo:first');
        var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
        var newComboBoxIndex = thisComboBoxIndex + 1;
    
        $('.parentCombo' + thisComboBoxIndex).remove();
    
        if (selectedValue !== '') {
            newComboBox.attr('data-index', newComboBoxIndex);
            newComboBox.attr('id', 'combo' + newComboBoxIndex);
            newComboBox.addClass('parentCombo' + thisComboBoxIndex);
            newComboBox.find('option[val="' + selectedValue + '"]').remove();
            $('body').append(newFieldset);
        }
      }     
    });​
    

    There are some details probably not exactly the way you need it, but in general this is the approach I'd recomment.

    Find the updated Fiddle here: http://jsfiddle.net/JaVVe/8/

提交回复
热议问题