【问题标题】:How the rails select box selected option is giving from coffee filerails选择框选择的选项如何从咖啡文件中给出
【发布时间】:2016-06-15 05:39:51
【问题描述】:

在 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))

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

谢谢

【问题讨论】:

  • 要明确一点 - 您希望预先选择哪个特定选项?如果您的 JS 代码中已经知道该选项,请参阅下面的答案。如果希望通过 AJAX 传递所选用户的 id,则可以根据传递方式轻松修改以下代码。

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


【解决方案1】:

选中的选项设置为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

有关使用 jQuery 设置 selected 属性的更多详细信息,请参阅 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2020-03-03
    相关资源
    最近更新 更多