JSFiddle - React, Tailwind, and code Playground
by Evgeniy Lukovsky
HTML
<script src="http://localhost/share/jquery.serializejson.js"></script>
<div class="hidden">
<div class="main-template">
<hr>
<label>name</label>
<input name="field[][title]" />
<label>key</label>
<input name="field[][key]" />
<button class="add-option" type="button">add option</button>
</div>
<div class="option-template">
<div class="option">
<input type="text" name="field[][option][][name]">
<input type="text" name="field[][option][][value]">
<button onclick="$(this).closest('.option').remove()">
X
</button>
</div>
</div>
</div>
<form id="test">
</form>
<button class="add-field">
Add field
</button>
<button class="check">
Check
</button>
<div id="result">
</div>
CSS
.hidden {
display: none;
}
CoffeeScript
window.addEventListener 'load', ->
form = $('#test')
mainTemplate = $('.main-template')
optionTemplate = $('.option-template')
new OptionsForm(form, mainTemplate, optionTemplate)
class OptionsForm
constructor: (@form, @fieldTemplate, @optionTemplate) ->
@fieldNum = 0
$('.add-field').on 'click', @addField
$('.check').on 'click', @check
addField: =>
@form.append(@replaceItemId(@fieldTemplate.html()))
do => @addOptionToField(@form, @fieldNum++)
replaceItemId: (html, itemId=@fieldNum) =>
html.replace(/field\[\]/g, "field#{itemId}]")
addOptionToField: (form, fieldNum) =>
optionNum = 0;
@form.find('.add-option').last().on 'click', (e) =>
html = @replaceItemId(@optionTemplate.html(), fieldNum)
html = html.replace(/option\]\[\]/g, "option][#{optionNum++}]")
$(html).insertAfter(e.currentTarget)
check: ->
options =
useIntKeysAsArrayIndex: true
parseAll: true
result = $('#test').serializeJSON(options)
$('#result').html(JSON.stringify(result))