Skip to content

Instantly share code, notes, and snippets.

@ricsirigu
Last active November 12, 2016 19:44
Show Gist options
  • Save ricsirigu/6639832c7dc182b07038be67602d37f2 to your computer and use it in GitHub Desktop.
Save ricsirigu/6639832c7dc182b07038be67602d37f2 to your computer and use it in GitHub Desktop.
An example with the Lift framework on how to dynamically load the content of a select according to the value of another one.
<div id="main" data-lift="surround?with=default;at=content">
<div data-lift="DynamicSelect">
<h2>Categories Chooser</h2>
<form>
<input type="text" placeholder="email" name="email">
<div name="choose-categories">
<select id="select-categories">
<option value="">Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="select-subcategories">
<option value="">Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button type="submit">Save</button>
</div>
</form>
</div>
</div>
package code.snippet
import net.liftweb.http.SHtml
import net.liftweb.http.SHtml.SelectableOption
import net.liftweb.http.js.JsCmd
import net.liftweb.http.js.JsCmds.Alert
import net.liftweb.util.Helpers._
/**
* Created by Riccardo Sirigu on 11/11/2016.
*
* An example on how to dynamically set the content of a select, according to the value of another one
*/
object DynamicSelect {
val categories = List(("food", "Food"), ("adventure", "Adventure"))
val subcategories = Map(
"food" -> List(("pizza", "Pizza"), ("streetfood", "Street food")),
"adventure" -> List(("hiking", "Hiking"), ("beach", "Beach"), ("camping", "Camping"))
)
def getSubcategories(category: String): Seq[SelectableOption[String]] = {
subcategories.filter(_._1 == category).getOrElse(category, Nil)
}
var chosenCategory = ""
var chosenSubcategory = ""
def render = {
def processSubmit: JsCmd = {
Alert(s"Category $chosenCategory, subcategory $chosenSubcategory")
}
SHtml.makeFormsAjax andThen
"@choose-categories" #> SHtml.idMemoize { select =>
def updateSelect(category: String) = {
chosenCategory = category
select.setHtml
}
"#select-categories" #> SHtml.ajaxSelect(categories, Some(chosenCategory), updateSelect) &
"#select-subcategories" #> SHtml.select(getSubcategories(chosenCategory), Some(chosenSubcategory), chosenSubcategory = _)
} &
"type=submit" #> SHtml.ajaxSubmit("Save", processSubmit _)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment