コントローラからjsに値を渡す方法
@json
を利用するフロント側
<script> let companies = @json($companies); </script>
-js側 - companiesにhtmlで指定した値がjson形式で入っている。
$(document).on("change", ".select-company", function(){ let val = $(this).val() companies.forEach(company => { if(val == company.id) { company.stores.forEach(store => { select.append($('<option>').attr({value: store.id}).text(store.title)) }); } }); });
<data-xxx=aaa>を利用する
フロント側
- data-xxxで値を入力する。
<button type="button" class="blue-btn edit-btn" data-toggle="moda" data-target="#editAccount" data-userid="{{$user->id}}" data-role="{{implode(',', $user->roles->pluck('id')->all())}}" data-canly-role="{{Encore\Admin\Auth\Database\Role::getFirstCanlyRole($user->roles->pluck('id')->all())}}" data-companies="{{implode(',',$user->companies->pluck('id')->all())}}"> 編集 </button>
-js側
- $(this).data('userid');
みたいな感じで取得できる。
$('button.edit-btn').click(function () { // form の action を調整する const userId = $(this).data('userid'); const orgAction = $('#route-account-update').val(); $('#form-edit').attr('action', orgAction + '/' + userId); // role をセットする const role = $(this).data('canly-role'); $("#accounts_edit_role_select").val(role); // 会社情報をクリアする const rowBakup = $('.row-company-select:last-child'); $(".companies-to-edit").children().remove(); $(".companies-to-edit").append(rowBakup); // 所属する companies 分だけ行を追加する const companies = ($(this).data('companies') + '').split(','); $.each(companies, function (index, val) { if (0 < index) { copyCompanyRow(); } $(`.row-company-select:last-child select option[value='${val}']`).prop('selected', true); }); });