redshot redshot - 19 days ago 8
HTML Question

How to set the selected value of Select Option in jQuery?

I am retreiving users and their id in Laravel. I retrieved the selected user ID and their full names. I want to set the selected option according to the current ID.

This is the value of the current user ID:

<input class="selected-user" type="input" value="{{$selectedUser}}" readonly />


This is my select code in Laravel Blade:

<div class="form-group required">

{!! Form::label('user_name', 'Assigned to', ['class' => 'control-label required']) !!}

<div class="controls">

<select class="form-control form-field-username form-field-user-edit form-field-users">
@foreach($users as $user)
<option value="{{$user->id}}">{{$user->getFullNameAttribute()}} </option>
@endforeach
</select>

</div>

</div>


This is my jquery code:

var selectedUser = $('.selected-user').val();

$('.form-field-user-edit > option[value="selectedUser"]').attr('selected','selected');


The above code is not working.

I want to mark the select selected option according to the value .selected-user

Answer

Try this.. You can select the option from server side

<select class="form-control form-field-username form-field-user-edit form-field-users">
    @foreach($users as $user)
         <option value="{{$user->id}}" {{ $selectedUser== $user->id ? 'selected="selected"' : '' }}>{{$user->getFullNameAttribute()}} </option>
    @endforeach 
</select>
Comments