我想根据所选的用户选项在文本框中显示数据的作用。例如,一个用户,担任项目经理。然后在选择用户时,文本框将显示角色管理器。但是问题是当我选择第一个用户时,他在文本框中显示了正确的数据。但是更改用户选择时,文本框不会更改,仅显示基于第一个选择的数据。怎么了??
我想根据所选用户在文本框中显示角色
我的观点
<div class="form-group">
<label>Name *</label>
<select class="form-control select2" style="width: 100%;" name="user_id" id="user_id">
<option selected="selected" value="user_id">Select One</option>
@foreach($users as $id => $user)
<option value="{{$id}}" data-price="{{$user_roles->name}}">{{$user}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="">Role *</label>
<input type="text" name="name" id="name" class="form-control" autocomplete="off" readonly>
</div>
脚本
<script type="text/javascript">
$('#user_id').on('change', function(){
var price = $(this).children('option:selected').data('price');
$('#name').val(price);
});
</script>
控制器
$projects = Project::pluck('project_name', 'id');
$users = User::pluck('name', 'id');
$user_roles = auth()->user()->role;
return view ('teams.create', compact('projects', 'users', 'user_roles'));
模型用户
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Presence;
use App\Models\Project;
use App\Productivity;
use App\Sick_leave;
use App\Annual_leave;
use App\Models\Team;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function presence()
{
return $this->hasOne(Presence::class, 'astrowatch', 'user_id', 'presence_id');
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function permission()
{
return $this->hasMany(Permission::class);
}
public function teams()
{
return $this->belongsToMany(Team::class, 'user_teams');
}
public function spent_time()
{
return $this->belongsToMany(Spent_time::class, 'astrowatch', 'user_id', 'spent_time_id');
}
public function projects()
{
return $this->belongsToMany(Project::Class, 'user_projects');
}
}
答案 0 :(得分:1)
将您的JS更改为此:
$(function() {
$('#user_id').on('change', function(){
var price = $(this).data('price');
$('#name').val(price);
});
});
-编辑-
更改此
控制器:
$users = User::all();
查看:
@foreach($users as $user)
<option value="{{$user->id}}" data-price="{{$user->role->name}}">
{{$user->name}}
</option>
@endforeach