javascript - Rails 选择框选择的选项如何从咖啡文件中给出

标签 javascript jquery ruby-on-rails-4 coffeescript

在 ajax 成功后的 js.coffee 文件中,我需要将值放入选择特定名称的选择框中。

_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:

$.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))

现在,用户全名列在选择框中,但我如何给出显示特定用户名的选定选项。

谢谢

最佳答案

所选选项已设置 by using the selected attribute .

假设要选择的用户的 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

参见here有关使用 jQuery 设置 selected 属性的更多详细信息。

关于javascript - Rails 选择框选择的选项如何从咖啡文件中给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746036/

相关文章:

Javascript 图像查看器在 Internet Explorer 中不起作用

javascript - 获取 child 的 parent 的 index() 值

ruby - 使用 AjaxDatatablesRails::Extensions 时未初始化的常量

ruby-on-rails - 如何在 ActiveSupport::Concern 中获取类名?

ruby-on-rails - 无法推送到 Heroku:Sprockets::FileNotFound:找不到 application.css

javascript - 使用 .on() 将变量传递给函数

javascript - 我如何使用javascript写入xml

javascript - 用 JavaScript 制作一个 Discord 机器人 : Attempting to make a game of wordchain between two players

jquery - 我想连续切换选定列的第一个子项的类

javascript - 使用 goTo() 条件 if/else 检查跳过 Bootstrap 中的步骤