Reputation: 845
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>
jQuery
$('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);
}
}
});
This code is working and is creating a new combobox everytime the one before is filled.
How can I have a linebreak every two dropdown? like this:
And how can I force it to fill always an even number of comboboxes. Eg. If it is only 3 combobox filled, must alert error.
Upvotes: 2
Views: 282
Reputation: 2113
This assumes you put your select boxes in a container that only holds the select boxes and the br's. (updated with validation)
$('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);
}
$('body br').remove();
$('body select:odd').after($('<br />'));
}
validate();
});
function validate() {
var count = $('body select[value!=""]').length;
if (count > 0 && count % 2 == 0)
$('#ok').text('OK!');
else
$('#ok').text('Not an even number selected');
}
Upvotes: 2
Reputation: 13544
Look at this Demo: http://jsfiddle.net/JaVVe/15/
i = 2;
$('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);
i++
if (Math.floor(i/2) < +i/2){
$('body').append('<hr />');
}
}
}
});
Upvotes: 1