Skip to content Skip to sidebar Skip to footer

How To Add Dynamically A Combobox Using Jquery

I've this working code which is creating one combobox: You can see it working here: jsfiddle $('body').on('change', '.combo', function() { var selectedValue = $(this).val();

Solution 1:

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><selectid="combo1"class="combo"data-index="1"><option></option><optionval="Opt1">Opt1</option><optionval="Opt2">Opt2</option><optionval="Opt3">Opt3</option></select><selectid="combo2"class="combo"data-index="2"><option></option><optionval="Opt1">Opt1</option><optionval="Opt2">Opt2</option><optionval="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/

Solution 2:

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.

Post a Comment for "How To Add Dynamically A Combobox Using Jquery"