dynamic drop down list jquery code example
Example 1: jquery dynamic drop down list example
HTML:
<div class="col-md-4" >
<select class="company">
<option value=''><strong>Name</strong></option>
<option value="Company A">Company A</option>
<option value="Company B">Company B</option>
</select>
</div>
<div class="col-md-4" >
<select class="product">
<option value=''><strong>Products</strong></option>
</select>
</div>
JavaScript
var series = [
{name: 'Company A', product: 'A1'},
{name: 'Company A', product: 'A2'},
{name: 'Company A', product: 'A3'},
{name: 'Company B', product: 'B1'},
{name: 'Company B', product: 'B2'}
]
$(".company").change(function(){
var company = $(this).val();
var options = '<option value=""><strong>Products</strong></option>';
$(series).each(function(index, value){
if(value.name == company){
options += '<option value="'+value.product+'">'+value.product+'</option>';
}
});
$('.product').html(options);
});
Example 2: dynamic select option dropdown in jquery
var temp = "myValue";
var newOption = $('<option>');
newOption.attr('value', temp).text(temp);
$('#dptcentres_edit').append(newOption);
$("#dptcentres_edit > [value=" + temp + "]").attr("selected", "true");