简体   繁体   中英

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.

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

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 .

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM