Skip to content

Instantly share code, notes, and snippets.

@Shadowfiend
Created February 26, 2013 20:58
Show Gist options
  • Save Shadowfiend/5042131 to your computer and use it in GitHub Desktop.
Save Shadowfiend/5042131 to your computer and use it in GitHub Desktop.
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