选择2搜索框

时间:2013-02-19 18:40:08

标签: coffeescript jquery-select2

我遇到以下功能的格式问题。正如您将在下面看到的,它主要起作用,只是搜索框的格式不是我想要的(我想要复制类型的Twitter Bootstrap功能):

用户可以在搜索框中输入书名,在搜索框下方的下拉菜单中选择要从中选择的书籍(通过ajax),然后选择书籍。在下拉列表中选择书籍后,表格将填充书籍信息。就像这样:

enter image description here

我的问题是select2会自动更改搜索输入的格式(在搜索框中的所选项目周围添加css)。见这里:

enter image description here

问题

我知道这并不是Select2的用途,但我希望将搜索框的值设置为“rails”,与我输入时的方式完全一致(第一次截图)。 如何保持常规输入格式?

详细信息:

这是我到目前为止的coffeescript代码(它具有异步加载图片和格式化选择):

jQuery ->

  get_image = (unique_id, image_url) ->
    img = $("<img  />").load(->
      $(".#{unique_id} .typeahead_photo_wrapper").html(img)
    ).error(->
      $(".#{unique_id} .typeahead_photo_wrapper").html("No preview")
    ).addClass('typeahead_photo').attr({src: image_url}).fadeIn(500)


  format_item = (book) ->
    console.log book
    itm = ''
    itm += "<div class='typeahead_wrapper #{book.isbn}'>"
    itm += "<div class='typeahead_photo_wrapper'>"
    itm += "<div class='typeahead_photo'>...</div>"
    itm += "</div>"
    itm += "<div class='typeahead_labels'>"
    itm += "<div class='typeahead_primary'>#{book.title}</div>"
    itm += "<div class='typeahead_secondary'>#{book.author}</div>"
    itm += "</div>"
    itm += "</div>"

    get_image(book.isbn, book.image)
    itm


  update_with_item = (item) ->
    keywords = $("#learning_item_book_search").val()
    # console.log item

    $("#new-book #learning_item_unique_identifier").val(item.isbn)
    $("#new-book #learning_item_source").val(item.source)
    $("#new-book #learning_item_name").val(item.title)
    $("#new-book #learning_item_description").val(item.description)
    $("#new-book button").focus()
    item.title



  retrieve_books = (data) ->
    books = []
    $.each data, (i, item) ->
      books.push(
        id: item.id
        isbn: item.isbn
        title: item.title
        author: item.authors
        description: item.description
        image: item.volume_info.imageLinks.smallThumbnail
      )
    books


  $("#learning_item_book_search").select2({
    minimumInputLength: 2
    tags: true
    ajax:
      url: "/raw_items/fetch_books"
      dataType: 'json'
      quietMillis: 200
      data: (term, page) ->
        query: term
      results: (data, page) ->
        return {results: retrieve_books(data)}
    maximumSelectionSize:1
    formatResult: format_item
    formatSelection: update_with_item
    formatInputTooShort: (term, minLength) ->
      "Searching book on Google books"
    dropdownCssClass: 'typeahead'
  })

2 个答案:

答案 0 :(得分:2)

你可以将select2置于多选模式 - 这将使它看起来像你想要的常规文本字段。使用maximumSelectionSize:1选项将选择限制为单个项目。在原始html控件上使用'change'事件来填充表单。

答案 1 :(得分:0)

format_item添加一行

$("#learning_item_book_search").select2('val', '')

对于多选

$("#learning_item_book_search").select2('val', [])

它会保留搜索字词,而不是添加所选项目。