[英]How to set the selected value of Select Option in jQuery?
I am retreiving users and their id in Laravel. 我正在Laravel中检索用户及其ID。 I retrieved the selected user ID and their full names.
我检索了所选的用户ID及其全名。 I want to set the selected option according to the current ID.
我想根据当前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: 这是我在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: 这是我的jQuery代码:
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 我想根据.selected-user值标记select selected选项
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>
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/option
You should instead do this on the server side using the html. 相反,您应该使用html在服务器端执行此操作。 The link I pasted is about the tag, and down the list you see an attribute called "selected".
我粘贴的链接与标签有关,在列表下方,您看到了一个称为“选定”的属性。 if this is present in your tag, it will be selected:
如果您的标签中包含此标签,则将其选中:
<option value="?" selected> This option is selected </option>
You just have to change the line of code from, 您只需要更改以下代码行,
$('.form-field-user-edit > option[value="selectedUser"]').attr('selected','selected');
to 至
$('.form-field-user-edit > option[value="selectedUser"]').attr('selected',true);
Try this: 尝试这个:
var selectedUser = $('.selected-user').val();
$('.form-field-user-edit > option[value="'+ selectedUser +'"]').prop('selected', true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.