Reputation: 845
Is there a chance to have a combobox, which every time I select something in there, it opens a new one, etc, until no more data to select?
(options must not be repeated)
Combo1 - (opt1-opt2-opt3) - selected opt1
Combo2 - (opt2-opt3) - selected opt3
Combo3 - (opt2)
Comboboxes should be populated by querys using php and mysql.
How can I do it ? Cheers!
Upvotes: 1
Views: 2253
Reputation: 15804
Here is some jquery that will do this:
HTML
<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>
Javascript
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if ($(this).find('option').size() > 2) {
var newComboBox = $(this).clone();
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(newComboBox);
}
}
});
Explanation
// Adds an event listener to each combo box that is created dynmically
$('body').on('change', '.combo', function() {
// Gets this selected value
var selectedValue = $(this).val();
// Checks if there are enough options left to create another combo box
if (selectedValue !== '' && $(this).find('option').size() > 2) {
// Clones the just selected combo box and get the current and next combo index
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
// Removes any "children" combo boxes
$('.parentCombo' + thisComboBoxIndex).remove();
// Checks if a blank value is not selected to create another combo box
if (selectedValue !== '' && $(this).find('option').size() > 2) {
// Gives this new combo box the correct id, index, parent class
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
// Removes the selected option from the new combo box
newComboBox.find('option[val="' + selectedValue + '"]').remove();
// Adds the combo box to the page. Disco!
$('body').append(newComboBox);
}
}
});
Upvotes: 3