Skip to content

Instantly share code, notes, and snippets.

@Shadowfiend
Created February 26, 2013 20:58
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
ajaxOnSubmit function to use in CssSelectorTransforms to add ajaxSubmit behavior to both button and input submit elements.
package net.liftweb.http
import scala.xml._
import net.liftweb.common._
import js._
import net.liftweb.util.Helpers._
object FormHelpers {
/**
* Add appropriate attributes to an input type="submit" or button
* element to make it submit an ajaxForm correctly and return a JsCmd
* to the client.
*
* Example:
*
* <pre>"type=submit" #> ajaxOnSubmit(() => Alert("Done!"))</pre>
*/
def ajaxOnSubmit(func: () => JsCmd): (NodeSeq)=>NodeSeq = {
import S._
val fgSnap = S._formGroup.get
(in: NodeSeq) => S._formGroup.doWith(fgSnap) {
def runNodes(ns: NodeSeq): NodeSeq = {
def addAttributes(elem: Elem, name: String) = {
val clickJs = "liftAjax.lift_uriSuffix = '" + name + "=_'; return true;"
elem % ("name" -> name) % ("onclick" -> clickJs)
}
ns.flatMap {
case Group(nodes) => runNodes(nodes)
case e: Elem if (e.label == "button") ||
(e.label == "input" && e.attribute("type").map(_.text) == Some("submit")) =>
_formGroup.is match {
case Empty =>
formGroup(1)(fmapFunc(func)(addAttributes(e, _)))
case _ => fmapFunc(func)(addAttributes(e, _))
}
}
}
runNodes(in)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment