[英]How the rails select box selected option is giving from coffee file
In a js.coffee file after an ajax success, i need to put values to a select box with selected a particular name. 在ajax成功之后的js.coffee文件中,我需要将值放到选择了特定名称的选择框中。
_form.html,erb : _form.html,erb :
<%= f.select(:user_id, Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.collect {|u| [ u.full_name, u.id ] }, selected: current_user.id)%>
items.js.coffee : items.js.coffee :
$.ajax '/users.json',
type: 'GET', data: {"from_prod_bu" : selecteditemId},
success: (data) ->
userSelectBox = $('#prod_user_id')
userSelectBox.html('')
if data.length == 0
userSelectBox.append($('<option>').text('').attr('value', ''))
else
$.each data, (index,el) ->
userSelectBox.append($('<option>').text(el.firstname+' '+el.lastname).attr('value', el.id))
Now, the user fullname is listing in the select box, but how can i give the selected option for displaying a particular username . 现在,用户全名将显示在选择框中,但是我如何才能给出用于显示特定用户名的所选选项。
Thanks 谢谢
The selected option is set by using the selected
attribute . 通过使用selected
属性来设置selected选项。
Suppose that the id
of the user to be selected is stored in the selectedUserId
variable within your JavaScript - then the following code should work: 假设要选择的用户的id
存储在JavaScript的selectedUserId
变量中,那么以下代码应该可以工作:
success: (data) ->
userSelectBox = $('#prod_user_id')
userSelectBox.html('')
if data.length == 0
userSelectBox.append($('<option>').text('').attr('value', ''))
else
$.each data, (index, el) ->
option = $('<option>')
.text(el.firstname + ' ' + el.lastname)
.attr('value', el.id)
if el.id == selectedUserId
option.attr 'selected', 'selected'
userSelectBox.append option
See here for more details on setting the selected
attribute with jQuery. 有关使用jQuery设置selected
属性的更多详细信息,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.