Ad

Laravel Blade - How To Add "selected" To Option Form Menu On A Dynamic Modal

- 1 answer

I'm sending data to my modal using data- attributes on my modal button.

In my "edit" modal I have a form that has a select menu where I need to return if an option is already selected.

I can do this normally using blade like this...

@foreach($companyUsers as $manager)
   <option id="manager-option" value="{{ $manager->id }}" {{ $manager->id == $user->manager_id ? 'selected' : '' }}> {{ $manager->userFormatted() }}</option>
@endforeach

But I need to insert the $user->manager_id dynamically via js. So here is my js

$('#editUser').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var user = button.data('user')
  var userManager = button.data('user-manager')

  var modal = $(this)
  modal.find('.k-form').attr('action', '/usermanagement/' + user)
  modal.find('#manager-option').attr('selected', userManager) // here i'm stuck
})

So where I have modal.find('.manager-option').attr(userManager) I need to somehow replace $user->manager_id in my blade file with the variable from my js userManager

Ad

Answer

Was able to fix this with @Tim Lewis suggestions.

Blade:

@foreach($companyUsers as $manager)
    <option class="manager-option-{{ $manager->id }}" value="{{ $manager->id }}"> {{ $manager->userFormatted() }}</option>
@endforeach

JS:

$('#editUser').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget)
    var user = button.data('user')
    var userName = button.data('user-name')
    var userManager = button.data('user-manager')

    var modal = $(this)
    modal.find('.k-form').attr('action', '/usermanagement/' + user)
    modal.find('.modal-title').text('Edit: ' + userName)
    modal.find('.manager-option-' + userManager).attr('selected', true)
})
Ad
source: stackoverflow.com
Ad