Reputation: 7138
As you in sample above I have placeholder (option without value) to say eg. Select Subcategory
but as soon as I change my category value result of subcategories will show.
What I want is when I select category in subcategory dropdown still says Select Subcategory
but under that be loaded result of chosen category. In simple words:
Instead of showing results directly, shows placeholder option and results be under it.
here is my codes:
// HTML
<label for="specification_id">specifications</label>
<select name="specification_id" class="form-control">
<option value="">Select Specification</option>
</select>
// JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('select[name="subcategory_id"]').on('change', function() {
var subcategoryID = $(this).val();
if(subcategoryID) {
$.ajax({
url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="specification_id"]').empty();
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>"
);
});
}
});
}else{
$('select[name="specification_id"]').empty();
}
});
});
</script>
Upvotes: 1
Views: 67
Reputation: 884
After emptying out the item make sure to append the blank placeholder back in it:
else{
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
}
or just skip it when clearing the select in the first place:
else{
$('select[name="specification_id"]').not(':first').remove();
}
i forgot the empty()
in the success:
function:
success:function(data) {
$('select[name="specification_id"]').not(':first').remove();
//...
or:
success:function(data) {
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
//...
Upvotes: 1
Reputation: 1432
Here your option values are empty because you Call empty function. So you can dynamically select option "Select specification " Following procedure works fine for me, try this way
success:function(data) {
$('select[name="specification_id"]').empty();
$('select[name="specification_id"]').append("<option
class='form-control' selected value=' '>Select
Specification </option>" );
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+
value['id'] +"'>"+ value['title'] +"</option>"
);
});
Thank you
Upvotes: 0