[英]How to append data to form collective select optgroup tag with jquery
我正在嘗試將基於 seclect 下拉列表的數據附加到另一個選擇。 一切正常,但我發現將數據附加到第二個選擇時遇到困難。 任何幫助接近它的幫助都會有很大幫助
// The select that initiates onchange
{!! Form::select('item_inventory', array(1 => 'Asset', 2 => 'GL'), null, ['id'=> 'item-modules', 'class' => 'form-control de-account-select2', 'placeholder' => trans('general.form.select.field', ['field' => trans_choice('general.items', 1)])]) !!}
//The data that should be updated on response success
{!! Form::select('item[' . $item_row . '][name]', array(1=>'asset 1'), null, ['id'=> 'item-name-' . $item_row, 'class' => 'form-control', 'placeholder' => trans('general.form.select.field', ['field' => trans_choice('general.accounts', 1)])]) !!}
//JQuery code
$(document).on('change', '#item-modules', function () {
$.ajax({
url: "{{url('expenses/Accounts') }}",
type: 'GET',
dataType: 'JSON',
data: 'item_module_id=' + $(this).val(),
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
success: function (data) {
let json = data.accounts;
console.log(json);
let html = "";
for (let option in json) {
html += `<optgroup label="` + option + `">`;
json[option].forEach(function (item) {
html += `<option value="` +
item["Attrib_value"] + `" >` + item["Attrib_value"] + `</option>`
});
html += `</optgroup>`;
}
$('#item-name-' + item_row).html(html);
}
});
Console.log 響應數據
Depreciation:
41: "700 - Depreciation"
Direct Costs:
20: "500 - Costs of Goods Sold"
Expense:
21: "600 - Advertising"
22: "605 - Bank Service Charges"
23: "610 - Janitorial Expenses"
24: "615 - Consulting & Accounting"
首先在函數定義之后在ajax請求頂部定義下拉變量。
$(document).on('change', '#item-modules', function () {
let dropdown = $('#id_of_second_select');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Set default select</option>');
dropdown.prop('selectedIndex', 0);
發布變量並進入ajax后,在成功函數之后,使用this添加每個變量。
$.each(json, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry).text(key));
})
這就是我修改我的 JQUERY 並為我工作的方式,我錯過了一些更精細的細節```
$(document).on('change', '#item-modules', function () {
$.ajax({
url: "{{url('expenses/Accounts') }}",
type: 'GET',
dataType: 'JSON',
data: 'item_module_id=' + $(this).val(),
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
success: function (data) {
let json = data.accounts;
let newDropdown = '';
for (let option in json) {
newDropdown += `<optgroup label="` + option + `">`;
$.each(json[option], function (key, item) {
newDropdown += `<option value="` + key + `" >` + item + `</option>`
});
newDropdown += `</optgroup>`;
}
$('#item-name-'+String(item_row-1)).append(newDropdown);
}
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.