Skip to content

Instantly share code, notes, and snippets.

@vtno
Created June 26, 2018 05:54
Show Gist options
  • Save vtno/cecf4263759bc255ae4fc62ae5257996 to your computer and use it in GitHub Desktop.
Save vtno/cecf4263759bc255ae4fc62ae5257996 to your computer and use it in GitHub Desktop.
// Bind it to click event of that specific button.
const buildFormFromTemplateBtn = (evt: Event,
addBtn: HTMLAnchorElement,
editorIdx: number,
isNewVersion: boolean = false) => {
if (evt.target instanceof window.HTMLAnchorElement) {
// Swap in the time to generate new unique key for a form input.
const time: number = new Date().getTime()
const uniqueId = addBtn.getAttribute('data-id') || ''
const regex: RegExp = new RegExp(uniqueId, 'g')
const templateString: string = addBtn.getAttribute('data-template-for-insertion') || ''
const uniqueTemplateString: string = templateString.replace(regex, time.toString())
const form: HTMLDivElement = document.createElement('div')
const htmlTemplate = stringToHtml(uniqueTemplateString)
if (htmlTemplate) {
form.innerHTML = htmlTemplate
if (!isNewVersion) {
const input: HTMLInputElement = ((form.querySelector('input[type="text"], textarea'): any): HTMLInputElement)
if (input) {
input.value = ''
}
}
// make sure new input is empty
const positionInput = ((form.querySelector('.position-input'): any): HTMLInputElement)
if (positionInput) {
// Index start from 0 so -1
const nextPosition: ?number = countEditorContent(editorIdx) - 1
positionInput.value = String(nextPosition)
}
return form.firstChild
} else {
throw new FormTemplateError('Cannot parsed template string from Rails: DynamicFormHelper')
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment