i need help. I would like to create dynamically selects with options depending the data i get from my REST API. The data is a JSONObject. How can i inject dynamically those selects into my html. Here is an example:
My JSON i get from REST API:
{
"Projects":[
"Project A",
"Project B",
"Project C"
],
"Variant":[
"Variant A",
"Variant B"
],
"Information":[
"Info 1",
"Info 2"
],
"Links":[
"Link 1",
"Link 2"]
}
Thats my template:
<div class="ui-field-contain" id="project-names">
</div>
Now i want to use jquery or angularjs to generate the selects Project, Variant, Information and Links, with their options.
It should be something like that:
<div class="ui-field-contain" id="project-names">
<label for="project">Project:</label>
<select name="project" id="project" data-native-menu="false">
<option value="Project A">Project A</option>
<option value="Project B">Project B</option>
<option value="Project C">Project C</option>
</select>
<label for="variant">Variant:</label>
<select name="variant" id="variant" data-native-menu="false">
<option value="Variant A">Variant A</option>
<option value="Variant B">Variant B</option>
</select>
<label for="Information">Information:</label>
<select name="Information" id="Information" data-native-menu="false">
<option value="Info A">Info A</option>
<option value="Info B">Info B</option>
</select>
<label for="select-1">Link:</label>
<select name="Link" id="Link" data-native-menu="false">
<option value="Link A">Link A</option>
<option value="Link B">Link B</option>
</select>
</div>
Is this possible?
Thanks.
EDIT My code so far:
var $htmlProjectNames = $("#project-names");
$btnGetProjects.on('click', function() {
$.ajax({
type : 'GET',
url: '/RestFulApi/api/v1/mcd/get-projects',
datatype : "json",
success : function(data) {
$.each(data, function(prefix, project) {
$htmlProjectNames.append(
'<label for' + perfix +'>' + prefix +'</label>\n'+
'<select name="'+prefix+ 'id="' + prefix +'"' + 'data-native-menu="false">'
);
});
}
});
});
Try:
$.ajax({
type : 'GET',
url: '/RestFulApi/api/v1/mcd/get-projects',
datatype : "json",
success : function(data) {
$.each(data, function (key, values) {
var template = '<label for="' + key.toLowerCase() + '">' + key + ':</label>' +
'<select name="' + key.toLowerCase() + '" id="' + key + '" data-native-menu="false">';
for(var i=0; i<values.length; i++){
template = template + '<option value="' + values[i] + '">' + values[i] + '</option>';
}
template = template + '</select>';
$("div#project-names").append(template);
});
}
});
Related
I have this form where I want to hide specific parts of it based on the subsubcategory_id selected but I can't seem to make it work.
I have a script that changes subcategory based on category selected and another one that changes subsubcategory based on subcategory selected.
The script for hiding parts of the form works but only for category that comes from the DB and not for subsubcategory that is affected by the first script. The value of the option element in the select just seems to register as empty for the 2nd script. What should I do to fix it?
<script type="text/javascript">
$(document).ready(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="subsubcategory_id"]').html('');
var d = $('select[name="subcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subcategory_name + '</option>');
});
},
});
} else {
alert('danger');
}
});
$('select[name="subcategory_id"]').on('change', function() {
var subcategory_id = $(this).val();
if (subcategory_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory/product') }}/" +
subcategory_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="subsubcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subsubcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subsubcategory_name + '</option>');
});
},
});
} else {
alert('danger');
}
});
});
</script>
// script to hide parts of the form
<script>
$(document).ready(function() {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
$("#test").change(function() {
var subsubcategory_id = $(this).val();
if (subsubcategory_id == 1) {
$('#fieldLaptop').show();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
} else if (subsubcategory_id == 2) {
$('#fieldLaptop').hide();
$('#fieldTablet').show();
$('#fieldPhone').hide();
} else if (subsubcategory_id == 3) {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').show();
} else {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
}
});
});
$("#test").trigger("change");
</script>
<form method="post" action="{{ route('product-store') }}" enctype="multipart/form-data">
#csrf
<div class="row mbn-20">
<div class="col-3 mb-20">
<label for="formLayoutUsername3">Brand</label>
<select name="brand_id" class="form-control">
<option value="" selected="" disabled="">Brand</option>
<option value="{{ $brand->id }}">
{{ $brand->brand_name }}
</option>
#endforeach
</select>
#error('brand_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</select>
</div>
<div class="col-3 mb-20">
<label for="formLayoutEmail3">Categorie</label>
<select name="category_id" class="form-control">
<option value="" selected="" disabled="">Category
</option>
<option value="{{ $category->id }}">
{{ $category->category_name }}
</option>
#endforeach
</select>
#error('category_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
<div class="col-3 mb-20">
<label for="formLayoutPassword3">SubCategory</label>
<select name="subcategory_id" class="form-control">
<option value="" selected="" disabled="">Select SubCategory
</option>
</select>
#error('subcategory_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
<div class="col-3 mb-20">
<label for="formLayoutAddress1">SubSubCategory</label>
<select name="subsubcategory_id" class="form-control" id="test">
<option value="" selected="" disabled="">Select SubSubCategory
</option>
</select>
#error('subsubcategory_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
</form>
Based on your explanation, I think you're looking for this:
$(document).on('change', '[data-child]', function() {
const selected_group = $(this).val();
let el = $(`#${$(this).attr("id")}`);
if (selected_group === null) {
el.hide();
} else {
el.show();
}
let child_select = $("#" + $(this).attr("data-child"));
value = child_select.find("option").hide().filter(function(i, e) {
return $(e).val().startsWith(selected_group);
}).show().eq(0).val();
child_select.val(value);
child_select.trigger("change");
});
$("[data-child]").eq(0).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="row m-4 justify-content-center">
<div class="col-3">
<span>Operating system</span>
<select data-child="niv1" class="selectdata form-control custom-select">
<option value="1-1">Android</option>
<option value="1-2">Linux</option>
<option value="1-3" selected>Windows</option>
</select>
</div>
<div class="col-3">
<span>System version</span>
<select id="niv1" data-child="niv2" class="selectdata form-control custom-select">
<option data-group="1-1" value="1-1-1">9.0 Pie</option>
<option data-group="1-2" value="1-2-1">Ubuntu</option>
<option data-group="1-3" value="1-3-1">Windows 7</option>
<option data-group="1-3" value="1-3-2">Windows 8</option>
<option data-group="1-3" value="1-3-3">Windows 10</option>
</select>
</div>
<div class="col-3">
<span>Edition</span>
<select id="niv2" data-child="niv3" class="selectdata form-control custom-select">
<option data-group="1-2-1" value="1-2-1-1">Trusty Tahr</option>
<option data-group="1-2-1" value="1-2-1-2">Xenial Xerus</option>
<option data-group="1-2-1" value="1-2-1-3">Bionic Beaver</option>
<option data-group="1-3-1" value="1-3-1-1">Windows 7 Home</option>
<option data-group="1-3-1" value="1-3-1-2">Windows 7 Pro</option>
<option data-group="1-3-2" value="1-3-2-1">Windows 8 Home</option>
<option data-group="1-3-2" value="1-3-2-2">Windows 8 Pro</option>
<option data-group="1-3-3" value="1-3-3-1">Windows 10 Home</option>
<option data-group="1-3-3" value="1-3-3-2">Windows 10 Pro</option>
</select>
</div>
<div class="col-3">
<span>Build</span>
<select id="niv3" data-child="niv4" class="selectdata form-control custom-select">
<option data-group="1-2-1-2" value="1-2-1-2-1">18.04 LTS</option>
<option data-group="1-3-1-1" value="1-3-1-1-1">Win 7 Home - A</option>
<option data-group="1-3-1-1" value="1-3-1-1-2">Win 7 Home - B</option>
<option data-group="1-3-1-2" value="1-3-1-2-1">Win 7 Pro - A</option>
<option data-group="1-3-1-2" value="1-3-1-2-2">Win 7 Pro - B</option>
<option data-group="1-3-2-1" value="1-3-2-1-1">Win 8 Home - A</option>
<option data-group="1-3-2-1" value="1-3-2-1-2">Win 8 Home - B</option>
<option data-group="1-3-2-2" value="1-3-2-2-1">Win 8 Pro - A</option>
<option data-group="1-3-2-2" value="1-3-2-2-2">Win 8 Pro - B</option>
<option data-group="1-3-3-1" value="1-3-3-1-1">Win 10 Home - A</option>
<option data-group="1-3-3-1" value="1-3-3-1-2">Win 1 Home - B</option>
<option data-group="1-3-3-2" value="1-3-3-2-1">Win 10 Pro - A</option>
<option data-group="1-3-3-2" value="1-3-3-2-2">Win 10 Pro - B</option>
</select>
</div>
</div>
So this is the way to make it work. If there is only one option You should probably trigger it manually after putting stuff in it so it runs with the first chosen option
The change is only called when the user changes it, and not after the AJAX runs. So in your case, you probably always want to call change to make sure your UI is in sync with what came from the server initially
$('select[name="subcategory_id"]').on('change', function() {
var subcategory_id = $(this).val();
if (subcategory_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory/product') }}/" +
subcategory_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="subsubcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subsubcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subsubcategory_name + '</option>');
});
// the tigger is set here for one option in the select !!!
$("#test").trigger("change");
},
});
} else {
alert('danger');
}
});
Then if there are multiple options the user will trigger them after so the first (initial) code would work.
Hi I have two dropdowns in my Html when I select my dropdown. my second dropdown needs to change related items.
My dropdown one has two item Domestic, international
second dropdown has three item INR, USD, EUR
When I change my first dropdown Domestic item selected need to display in my second dropdown INR Item only display other item need to hide.
Then I select an international item in my first dropdown that needs to display in my second dropdown USD, and EUR currency only displays. how to achieve it. (using jquery or javascript). My code below here.
<div class="input-group input-group-sm">
<select id="OrderType" asp-for="Type" title="Mode" class="form-control form-control-sm border selectpicker" onchange="GetCurrencybyType(this)">
<option id="DomId" value="1" selected>Domestic</option>
<option id="InterId" value="2">International</option>
</select>
</div>
<div class="input-group input-group-sm">
<select id="CurrencyType" asp-for="Currency" title="Mode" class="form-control form-control-sm border selectpicker">
<option id="InrId" value="1" selected>INR</option>
<option id="UsdId" value="2">USD</option>
<option id="EurId" value="2">EUR</option>
</select>
</div>
My Jquery function
function GetCurrencybyType(id) {
var value = id.value;
if (value == 2) {
$('#mySelect').children().remove().end()
.append('<option selected value="USD">USD</option>');
}
else {
$("option[value='2']").remove();
$('select[id=CurrencyType]').val('<option value="' + id.val + '">' + "INR" + '</option>');
}
//var value = id.value;
//var selectedCountry = $(this).children("option:selected").val();
//alert("You have selected the country - " + value);
//var InrIdValue = $("#InrId").val();
//if (value == "Domestic") {
// $("#CurrencyType").html("");
// var result = $("#CurrencyType").html("");
// alert(result);
// $("#CurrencyType").append($("<option />").val(InrIdValue).text(InrIdValue));
// var result1 = $("#CurrencyType").append($("<option />").val(InrIdValue).text(InrIdValue));
// alert(result1);
// //$('select[id=CurrencyType]').val(InrIdValue);
// //var result = $('select[id=CurrencyType]').val(InrIdValue);
// //alert(result);
// //$('select[id=CurrencyType]').val('<option value="' + InrIdValue + '">' + InrIdValue + '</option>');
//}
//else {
// alert("International");
//}
}
i not getting correct value in my UI please answer me.
Here is a working demo you could follow:
<div class="input-group input-group-sm">
<select id="OrderType" title="Mode" class="form-control form-control-sm border selectpicker" >
<option id="DomId" value="1">Domestic</option>
<option id="InterId" value="2">International</option>
</select>
</div>
<div class="input-group input-group-sm">
<select id="CurrencyType" title="Mode" class="form-control form-control-sm border selectpicker">
<option value="" selected>Select A Currency</option>
</select>
</div>
#section Scripts
{
<script>
$(function () {
var subjectObject = {
"1": [
"INR"
],
"2": [
"USD",
"EUR"
]
};
$('#OrderType').change(function () {
var OrderType = $(this).val()
var CurrencyType = subjectObject[OrderType] || [];
var html = $.map(CurrencyType, function (cnt) {
return '<option value="' + OrderType + '">' + cnt + '</option>'
}).join('');
$('#CurrencyType').html(html)
});
})
</script>
}
A JSFiddle you could check: https://jsfiddle.net/b6pe3vxq/
I have two dropdowns. The options of the latter are dependent on the values of the first.
<div class="col-lg-6 col-md-6 col-sm-6">
<select id="area" name="area" required>
<option value="">Select Area</option>
<option value="1">Area I: Vision, Mission, Goals, and Objectives</option>
<option value="2">Area II: Faculty</option>
<option value="3">Area III: Curriculum and Instruction</option>
<option value="4">Area IV: Support to Students</option>
<option value="5">Area V: Research</option>
<option value="6">Area VI: Extension and Community Involvement</option>
<option value="7">Area VII: Library</option>
<option value="8">Area VIII: Physical Plant and Facilities</option>
<option value="9">Area IX: Laboratories</option>
<option value="10">Area X: Administration</option>
</select>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<select id="parameter" name="parameter" required>
<option value="">Select Parameter</option>
</select>
</div>
I tried this javascript below but the problem is the options do not append to the second select even if I tried displaying the values using alert which works perfectly fine.
Does the CSS responsible for this?
<script type="text/javascript">
$('#area').on('change', function(){
console.log($('#area').val());
$('#parameter').html('');
var area = $('#area').val();
if(area == ""){
$('#parameter').append('<option value="">Select Area first</option>');
}else{
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>search/getParameters',
data: {area: area},
dataType: "json",
success: function(data){
$('#parameter').append('<option value=""></option>');
for (var i = 0; i < data.length; i++) {
alert(data[i])
$('#parameter').append('<option value="' + i + '">' + data[i] + '</option>');
}
}
});
}
});
</script>
Hi i'm trying to apply a callback to use on my dynamic select boxes instead of TimeOut
Currently i have 4 select options boxes(3 are dynamic options): City, District(options based on city options), Ward(options based on district options) and Street(options based on district options)
It's a search form so the next page form should has the previous form values, i use Django to determined if a previous form values are select , then if so it will add a hidden div with id="value-filter" in the template. And now i use the Jquery to check if that div exists to change the select options
If a user click on the city option then it will activate the city onchange event to call an api that populate District options with the corresponding city Id, Ward and Street options are the same but based on District options to call their api in order to populate their options.
$(document).ready(function() {
//call district api if city option is selected
$('select#city').change(function(event) {
$.getJSON("/api_get_districts/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- District --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#district").html(options);
});
});
//call ward and street api if district option is selected
$('select#district').change(function(event) {
$.getJSON("/api_get_wards/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- Ward --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#ward").html(options);
});
$.getJSON("/api_get_streets/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- Street --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#street").html(options);
});
});
// main one to handle select option if the div of a values is present in html
if ($('#district-filter').length) {
$('select#city').val("{{ filter_form_values.city |safe }}").change();
setTimeout(function() {
$('select#district').val("{{ filter_form_values.district |safe }}").change();
if ($('#ward-filter').length) {
setTimeout(function() {
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
}, 500);
}
if ($('#street-filter').length) {
setTimeout(function() {
$('select#street').val("{{ filter_form_values.street |safe }}").change();
}, 500);
}
}, 500);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Tỉnh </label>
<select class="form-control form-control-sm" name="city" id="city" required="">
<option selected="" disabled="">-- City --</option>
<option value="1">Hà Nội</option>
<option value="2">Hồ Chí Minh</option>
<option value="3">Bình Dương</option>
<option value="4">Đà Nẵng</option>
<option value="5">Hải Phòng</option>
<option value="6">Long An</option>
<option value="7">Bà Rịa Vũng Tàu</option>
<option value="8">An Giang</option>
<option value="9">Bắc Giang</option>
<option value="10">Bắc Kạn</option>
<option value="11">Bạc Liêu</option>
<option value="12">Bắc Ninh</option>
<option value="13">Bến Tre</option>
<option value="14">Bình Định</option>
<option value="15">Bình Phước</option>
<option value="16">Bình Thuận</option>
<option value="17">Cà Mau</option>
<option value="18">Cần Thơ</option>
<option value="19">Cao Bằng</option>
<option value="20">Đắk Lắk</option>
<option value="21">Đắk Nông</option>
<option value="22">Điện Biên</option>
<option value="23">Đồng Nai</option>
<option value="24">Đồng Tháp</option>
<option value="25">Gia Lai</option>
<option value="26">Hà Giang</option>
<option value="27">Hà Nam</option>
<option value="28">Hà Tĩnh</option>
<option value="29">Hải Dương</option>
<option value="30">Hậu Giang</option>
<option value="31">Hòa Bình</option>
<option value="32">Hưng Yên</option>
<option value="33">Khánh Hòa</option>
<option value="34">Kiên Giang</option>
<option value="35">Kon Tum</option>
<option value="36">Lai Châu</option>
<option value="37">Lâm Đồng</option>
<option value="38">Lạng Sơn</option>
<option value="39">Lào Cai</option>
<option value="40">Nam Định</option>
<option value="41">Nghệ An</option>
<option value="42">Ninh Bình</option>
<option value="43">Ninh Thuận</option>
<option value="44">Phú Thọ</option>
<option value="45">Phú Yên</option>
<option value="46">Quảng Bình</option>
<option value="47">Quảng Nam</option>
<option value="48">Quảng Ngãi</option>
<option value="49">Quảng Ninh</option>
<option value="50">Quảng Trị</option>
<option value="51">Sóc Trăng</option>
<option value="52">Sơn La</option>
<option value="53">Tây Ninh</option>
<option value="54">Thái Bình</option>
<option value="55">Thái Nguyên</option>
<option value="56">Thanh Hóa</option>
<option value="57">Thừa Thiên Huế</option>
<option value="58">Tiền Giang</option>
<option value="59">Trà Vinh</option>
<option value="60">Tuyên Quang</option>
<option value="61">Vĩnh Long</option>
<option value="62">Vĩnh Phúc</option>
<option value="63">Yên Bái</option>
</select>
</div>
<div class="form-group">
<label>District </label>
<div id="district-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="district" id="district">
<option selected="" disabled="">-- District --</option>
</select>
</div>
<div class="form-group">
<label>Ward </label>
<div id="ward-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="ward" id="ward">
<option selected="" disabled="">-- Ward --</option>
</select>
</div>
<div class="form-group">
<label>Street </label>
<div id="street-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="street" id="street">
<option selected="" disabled="">-- Street --</option>
</select>
</div>
Everything worked great but now i want to try to change my timeOut function in the if ($('#district-filter').length) {} to a callback. I had tried the following by using when() to apply callback:
if ($('#district-filter').length) {
$.when($('select#city').val("{{ filter_form_values.city |safe }}").change()).then(function() {
$.when($('select#district').val("{{ filter_form_values.district |safe }}").change()).then(function() {
if ($('#ward-filter').length) {
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
}
if ($('#street-filter').length) {
$('select#street').val("{{ filter_form_values.street |safe }}").change();
}
});
});
}
On page load the city is select and the District load but the district options didn't get select so the Ward and Street options also empty.
How do i use callback to wait for my Api to populate an options then select that option?
I had decided to just use normal callback and add the request api function in the check:
if ($('#city-filter').length) {
$('select#city').val("{{ filter_form_values.city |safe }}").change();
}
if ($('#district-filter').length || $('#ward-filter').length || $('#street-filter').length) {
$.getJSON("/api_get_district/", {
id: "{{ filter_form_values.city |safe }}"
}, function(j) {
var options = '<option selected disabled>-- District --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#district").html(options);
$('select#district').val("{{ filter_form_values.district |safe }}").change();
if ($('#ward-filter').length) {
$.getJSON("/api_get_ward/", {
id: "{{ filter_form_values.district |safe }}"
}, function(j) {
var options = '<option selected disabled>-- Ward --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#ward").html(options);
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
});
}
if ($('#street-filter').length) {
$.getJSON("/api_get_street/", {
id: "{{ filter_form_values.district |safe }}"
}, function(j) {
var options = '<option selected disabled>-- Street --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#street").html(options);
$('select#street').val("{{ filter_form_values.street |safe }}").change();
});
}
});
}
also add city check to the html:
<div id="city-filter" style="display: none"></div>
And now it worked but i will take any suggestion to improve it as answer(since calling api 2 times isn't consider a good idea)!
I have a small web app where I need to populate a dropdown list after selecting another right before.
For example this is the URL of the Ajax request http://localhost:8080/ajax/dropdown_model?brandId=0 and the JSON code looks like this:
[{"id":0,"name":"Z-400","brand":{"id":0,"name":"Lenovo"}}]
The code I used is this one:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var html = '';
$('select#brand').change(
function() {
$.getJSON("http://localhost:8080/ajax/dropdown_model", {
brandId : $(this).val(),
ajax : 'true'
}, function(data) {
html = '<option disabled="disabled" value="">Seleccionar modelo:</option>';
var len = data.length;
for ( var i = 0; i < len; i++) {
html += '<option value="' + data[i].id + '">'
data[i].id + ' : ' + data[i].name + '</option>';
}
html += '</option>';
$('select#model').html(html);
});
}); </script>
It should replace the content of the 2nd select tag adding into it the content of the JSON string.
Also this is the relevant part of the form (I'm using Spring and Thymeleaf):
<div class="brand" th:object="${lbra}">
<select name="brand" id="brand" >
<option value="">Seleccionar marca:</option>
<option th:each="brand : ${lbra}"
th:value="${brand.getId()}"
th:text="${brand.getId()}+' : '+${brand.getName()}"></option>
</select> </div>
<div class="model" id="modellist">
<select name="model" id="model">
<option value="" disabled="disabled" selected="selected">Seleccionar modelo:</option>
<option></option>
</select> </div>
I've removed some of the Spring variables for the sake of creating an example. You were missing a "+" after your dynamic option that is added to the HTML string (after html += '<option value="' + data[i].id + '">')..
var html = '';
$('select#brand').change(
function() {
$.getJSON("https://api.myjson.com/bins/ugf4v", {
brandId: $(this).val(),
ajax: 'true'
}, function(data) {
html = '<option disabled="disabled" value="">Seleccionar modelo:</option>';
var len = data.length;
for (var i = 0; i < len; i++) {
html += '<option value="' + data[i].id + '">' +
data[i].id + ' : ' + data[i].name + '</option>';
}
html += '</option>';
$('select#model').html(html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="brand">
<select name="brand" id="brand">
<option value="">Seleccionar marca:</option>
<option>Test Change</option>
</select>
</div>
<div class="model" id="modellist">
<select name="model" id="model">
<option value="" disabled="disabled" selected="selected">Seleccionar modelo:</option>
<option></option>
</select>
</div>