I've made the following and have a few questions:
Do I have some (big) mistakes in this approach? (bad practices, 'this code is trash'...)
1.1 If I do, can you suggest what to fix?
- Are appended element created in good way?
- Code in success function seems to be a little long. Any way to refactor?
CSS code
.no-display-table {
display: none;
}
HTML code
<div class="row">
...
<!-- empty div will hold <select> which will be crated on ajax success -->
<div class="append-select col-md-3"></div>
...
</div>
...
<!-- onLoad => 'display: none', <tr> will be dynamically crated on Ajax Success -->
<div class="row">
<div class="col-md-4 col-md-offset-2">
<table id="options-table" class="table table-striped">
<thead> <tr><th> Selected options </th></tr> </thead>
<tbody></tbody>
</table>
</div>
</div>
JavaScript code
$(function() {
$('#options-table').addClass('no-display-table');
$('#product-option-select').change(function() {
if($('.append-select select').length > 0)
$('.append-select select').remove();
var selectedOptionId = $(this).val();
$.ajax({
type: 'get',
url: '../option_types/' + selectedOptionId,
success: function(data) {
var element = '<select id="value-select" class="form-control">';
element += '<option selected disabled>Select value...</option>';
for(var i=0; i<data.length; i++) {
element += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
element += '</select>';
$('.append-select').append(element);
$('.append-select').on('change', '#value-select', function() {
$('#options-table').removeClass('no-display-table');
var selectedValue = $('#value-select option:selected').text();
var element = '<tr><td>' + selectedValue + '</td>';
element += '<td><a class="remove"> x </a></tr>';
$('#options-table tbody').append(element);
$('#options-table').on('mouseover', '.remove', function() {
$('.remove').css('cursor', 'pointer');
});
$('#options-table').on('click', '.remove', function() {
$(this).parent().parent().remove();
if($('#options-table tbody tr').length == 0)
$('#options-table').addClass('no-display-table');
});
});
}
});
});
});