Skip to content

Instantly share code, notes, and snippets.

@vgonda
Last active July 4, 2017 09:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgonda/8ae95f2f754e65f75fa7b4f18c1cedf4 to your computer and use it in GitHub Desktop.
Save vgonda/8ae95f2f754e65f75fa7b4f18c1cedf4 to your computer and use it in GitHub Desktop.
Example for Selectize.js blog post
<%= form_for @user, html: { "data-account-emails": @user.email_addresses.join(",") do |form| %>
<label>
Email<br>
<%= f.text_field :email, value: f.object[:email], class: "email-autocomplete" %>
</label>
<% end %>
jQuery ->
REGEX_EMAIL = new RegExp('^[^@\\s]+@([^@\\s]+\\.)+[^@\\W]+$')
KEY_RETURN = 13
selectize_options = () ->
options = {
persist: false
maxItems: null
maxOptions: 3
plugins: ['remove_button']
valueField: 'value'
searchField: 'value'
selectOnTab: true
disableDelete: true
render:
item: (item, escape) ->
return "<div class='email-item'><span>#{escape(item.value)}</span></div>"
option: (item, escape) ->
return "<div class='email-item'><span>#{escape(item.value)}</span></div>"
closeAfterSelect: true
createOnBlur: true
createFilter:
REGEX_EMAIL
create: true
onInitialize: ->
values = this.$input.parents("form").data("account-emails")
if values
for value in values.split(",")
this.addOption({value: value})
}
$(".email-autocomplete").selectize(selectize_options())
$(document).on('keydown', '.selectize-input input', (e) ->
if e.keyCode == KEY_RETURN
e.preventDefault()
)
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require selectize
//= require_tree ./public
class UsersController < ApplicationController
def edit
@user = User.find(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment