Skip to content

Instantly share code, notes, and snippets.

@korny
Last active May 29, 2024 08:02
Show Gist options
  • Save korny/5487129 to your computer and use it in GitHub Desktop.
Save korny/5487129 to your computer and use it in GitHub Desktop.
Simple prompt functionality for Rails / jQuery UJS, modelled after "confirm". Tested with Rails 4 (edge).
# Usage: link_to …, prompt: { message: 'Some message', default: 'default value', param: 'name of parameter' }
# The prompt will ask for "message" and use "default" as the default value.
# Unless user selects cancel, "param"=<new value> will be sent to the given path.
# Optionally, you can just use `prompt: "message"`.
$.rails.prompt = (message, defaultValue) ->
window.prompt message, defaultValue
$.rails.handlePrompt = (element) ->
config = element.data 'prompt'
message = config.message || config
defaultValue = config.default
param = config.param || 'value'
return true unless message
if $.rails.fire element, 'prompt'
value = $.rails.prompt message, defaultValue
callback = $.rails.fire element, 'prompt:complete', [value]
params = element.data('params') || {}
params[param] = value
element.data 'params', params
value && callback
allowAction = $.rails.allowAction
$.rails.allowAction = (element) ->
if element.data 'prompt'
$.rails.handlePrompt element
else
allowAction element
= link_to 'edit foo', path, method: :patch, remote: true, data: { prompt: { message: 'Enter a new value:', default: old_value, param: 'foo' } }
@volonterx
Copy link

Hello, I've added some code for links without "remote: true".
Please check my solution: https://gist.github.com/volonterx/d25f624cfcca86e3e9db

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment