Reputation: 845
Database
$mySql = "SELECT field FROM fields";
$result = mysql_query($mySql);
Html:
<select id="combo1" class="combo" data-index="1">
<option></option>
<?php
while($r = mysql_fetch_array($result))
{
echo "<option value=" .$r['field '] . ">".$r['field '] ."</option>";
}
?>
</select>
<div id="combos"></div>
jQuery
<script type="text/javascript">
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if (selectedValue !== '' && $(this).find('option').size() > 8) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('#combos').append(newComboBox);
}
});
</script>
Questions: This code is creating comboboxes with my database talble fields. My problem is that fields cant be repeated when selected once. Where is the error in the code? Or what am I thiking wrong?
It was supposed to be like that: http://jsfiddle.net/JaVVe/1/
Upvotes: 0
Views: 1518
Reputation: 611
on site example is
<option val="Opt1">
In your html it's value
attribute instead of val
so you need to change
newComboBox.find('option[val="' + selectedValue + '"]').remove();
to
newComboBox.find('option[value="' + selectedValue + '"]').remove();
Upvotes: 1
Reputation: 64526
The problem is you are checking size() > 8
, so for it work there must be more than 8 options. Change that to size() > 2
. Other than that your code will work.
The other problem is you aren't wrapping the option values in quotes. Add quotes:
echo "<option value=\"" .$r['field'] . "\">".$r['field'] ."</option>";
You also have a space after field:
$r['field ']
// ^ here, remove that
Upvotes: 1