可変長の追加フォームを作成する
の続き。
ついでだから動的にフォームを突っ込んでみる。
まずは build.sbt に下記を突っ込む。
coffeescriptOptions := Seq("bare")
Coffee コードをコンパイルする際に、ラップをしない操作。
で、coffee でざっくり作成
$(document).ready () -> startsWith = (str, prefix) -> str.indexOf(prefix) == 0; String.prototype.endsWith = (suffix) -> this.indexOf(suffix, this.length - suffix.length) != -1 class FormCpy @copyBefore: (copyElem, copyId, beforeId, templateFunction) -> nameFilter = (elem) -> name = String elem.name name.endsWith copyId nextIndex = $.grep($($(copyElem)), nameFilter).length gen = templateFunction(nextIndex) $(beforeId).before($(gen)) template = (id) -> """ <dl class=" " id="games_#{id}__name_field"> <dt><label for="games_#{id}__name">games[#{id}].name</label></dt> <dd> <input type="text" id="games_#{id}__name" name="games[#{id}].name" value=""> </dd> </dl> <dl class=" " id="games_#{id}__vendor_field"> <dt><label for="games_#{id}__vendor">games[#{id}].vendor</label></dt> <dd> <input type="text" id="games_#{id}__vendor" name="games[#{id}].vendor" value=""> </dd> </dl> """ $("#append").click(() -> FormCpy.copyBefore("input", "name", "#submit", template))
endsWith がデフォルトでプロトタイプにいたりいなかったり、、、地味に鬱陶しい。
正式に対応するなら
Matthew Brown : Javascript string endsWith()
後はフォームのボタン近辺に
<input id="submit" type="submit" value="送信!"/> <a id="append" href="#">フォーム追加アッ!</a>
ミッションコンプリート。