How to add dynamically a combobox using jQuery

后端 未结 2 1393
孤独总比滥情好
孤独总比滥情好 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:

    <fieldset>
      <select id="combo1" class="combo" data-index="1">
        <option></option>
        <option val="Opt1">Opt1</option>
        <option val="Opt2">Opt2</option>
        <option val="Opt3">Opt3</option>
      </select>
      <select id="combo2" class="combo" data-index="2">
        <option></option>
        <option val="Opt1">Opt1</option>
        <option val="Opt2">Opt2</option>
        <option val="Opt3">Opt3</option>
      </select>
    </fieldset>
    

    ​ 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/

    0 讨论(0)
  • 2021-01-20 05:17

    If you just want to double the amount of combo boxes you could use a for-loop and set their values depending on the value of the counter-variable.

    0 讨论(0)
提交回复
热议问题