Binding between UI and JavaScript: Different scopes? - javascript

I have a web app. In this app, I have a page of dynamically built editable items. I have the editing portion working just fine. My problem is, I'm unable to bind changes from the input element back to my data structure. I have a fiddle here. My relevant code looks like this:
var options = [];
$(document).ready(function() {
$(function() {
$.material.init();
});
// Initialize the options
options.push({ id:1, html:'' });
options.push({ id:2, html:'' });
options.push({ id:3, html:'' });
var optionEditors = $('.option-editor');
for (var i=0; i<optionEditors.length; i++) {
$(optionEditors[i]).summernote({
airMode: true,
popover: {
air: [
['font', ['bold', 'underline', 'clear']]
]
},
callbacks: {
onInit: function() {
var editor = $('.note-editor');
editor.addClass('form-control');
editor.bind('DOMSubtreeModified', onUpdate);
$(this).summernote('code', ' ');
var editable = editor.find('.note-editable');
editable.attr('data-id', $(this).attr('data-id'));
editable.attr('data-index', $(this).attr('data-index'));
}
}
});
}
});
function onUpdate(option) {
try {
var id = choice.target.getAttribute('data-id');
var index = choice.target.getAttribute('data-index');
alert(id + ' : ' + index)
options[index].html = choice.target.innerHTML;
} catch (ex) {
}
}
It's almost like the options variable is in a different scope. It's so weird. Basically, when the text in any of the input fields gets updated the options content should get updated as well. Such that when I click the Print button, I can see the contents of the options variable in the console window. I'm not sure what I'm doing wrong though.

var id = choice.target.getAttribute('data-id'); on this line choice is undefined. Maybe that's the problem?

Related

How to change fancytree SelectMode on a button click event?

I am using the a tree view/tree grid plugin which is called fancytree (Here is the link)
I initially (when the page loads) set the selectMode to 2 which allows the users to select multiple options.
// Init
$("#Organizations .OrgTree").each(function () {
var $this = $(this);
var organizationUnitId = $this.data("orgid");
//var treeData = JSON.parse($("#treeData_" + organizationUnitId).val());
$this.fancytree({
extensions: ["persist"],
selectMode: 2,
persist: {
expandLazy: true
store: "auto" 'session': sessionStore
},
icons: false,
checkbox: true,
toggleEffect: null, //disable animations
source: window["treeData_" + organizationUnitId], // treeData
lazyLoad: function (event, data) {
var node = data.node;
data.result = {
// Some data
};
}
});
});
What I want to do is, when I click on a button, I want to change the selectMode and set it to 1 or 3.
I have tried to read through the documentation and found this as well
But I won't work. Here is some code:
//Bind click to search button
$("#changeSelectModeBtn").click(function () {
debugger;
$("#Organizations .OrgTree").fancytree("getTree").visit(function (node) {
node.setSelected(false);
});
$("#Organizations .OrgTree").fancytree({ selectMode: 3 });
var selectedKeys = [];
$("#Organizations .OrgTree").each(function () {
var $this = $(this);
var orgTree = $(this).fancytree("getTree");
var selectedParentNodes = orgTree.getSelectedNodes();
for (node in selectedParentNodes) {
selectedKeys.push(selectedParentNodes[node].key)
}
// Save orgtree in hidden fields
var organizationUnitId = $this.data("orgid");
var treeData = orgTree.toDict(true);
window["treeData_" + organizationUnitId] = treeData.children; //$("#treeData_" + organizationUnitId).val(JSON.stringify(treeData.children))
});
if (selectedKeys) {
$("#HiddenOrganizationUnitIds").val(selectedKeys.join(","));
}
})
Can someone please help me?
Thanks in advance!
All options can be set dynamically using the jQuery widget pattern.
For example, you can use
$("#tree").fancytree("option", "selectMode", 3);
See also https://github.com/mar10/fancytree/wiki#configure-options

jquery Datatables checkbox get all checked rows

I have a datatable in which in which I'm trying to get all the checked rows. This table has row grouping and uses a checkbox plugin from gyrocode. I've tried the code listed on the api, but I had no luck. I only get the first record returned, regardless of what is selected. The code I used for the is shown below:
var tbl;
$(document).ready(function (){
tbl = $('#example').DataTable({
columnDefs: [{
targets: 0,
data: 2,
'checkboxes': {
'selectRow': true
}
},
{ "visible": false, "targets": 1 }],
select: {
style: 'multi'
},
order: [[1, 'asc']],
iDisplayLength: 10,
drawCallback: function () {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="6">' + group + '</td></tr>'
);
last = group;
}
});
}
});
});
function getSelected(){
alert(tbl.columns().checkboxes.selected().length);
}
I have the code in my jfiddle here. I'm not sure if their is interence between the checkbox and the row grouping? Please let me know where I am going wrong.
Note: The checkbox is based on the plugin by gyrocode The datatables is version 1.10.12
I'm too late to answer this question. But my answer can help others in the community.
//datatable has to be initialized to a variable
var myTable = $('#calltable').dataTable();
//checkboxes should have a general class to traverse
var rowcollection = myTable.$(".call-checkbox:checked", {"page": "all"});
//Now loop through all the selected checkboxes to perform desired actions
rowcollection.each(function(index,elem){
//You have access to the current iterating row
var checkbox_value = $(elem).val();
//Do something with 'checkbox_value'
});
I hope that helps.
I did a quick check and Eric Guan is correct. I'll just post a code snippet:
function getSelected() {
var selectedIds = tbl.columns().checkboxes.selected()[0];
console.log(selectedIds)
selectedIds.forEach(function(selectedId) {
alert(selectedId);
});
}
See: https://jsfiddle.net/nwmmbLso/3/
I just noticed you have duplicatie Student Id's which might also cause unexpected behavior from the library you are using. The code provided above should work if the Student Id's are unique.
Working and tested.
var id = "";
var oTable = $(".table").dataTable();
$(".check_quality:checked", oTable.fnGetNodes()).each(function() {
if (id != "") {
id = id + "," + $(this).data('id');
} else {
id = $(this).data('id');
}
});
Simple answer - use either table.rows( '.selected' ) or table.rows( {selected:true} )
var count = $('#datatable').DataTable().rows( '.selected' ).count();
var checked_rows = $('#datatable').DataTable().rows( '.selected' ).data();
for(var i=0; i<checked_rows.length; i++)
{
console.log( checked_rows[i] );
}
Document Link: https://datatables.net/reference/api/count()
for people still looking today for the answer
var rowcollection = table.columns(0).context[0].checkboxes.s.data;

How to create jQuery Datatable Drill-down rows?

In my MVC project, I am trying to use a single Datatable and collapse the rows for detail data as shown on Creating an expandable master-details table (jQuery DataTables and ASP.NET MVC integration - Part IV). On the other hand, I am looking for a similar examples of jQuery Datatable master-detail relations for ASP.NET MVC, but unfortunately I have not another suitable sample or tutorial from at least 50 pages on the web. Is there a similar examples like that? Thanks in advance...
I did similar work for one of the projects. I had one collapse/expand button that works for the whole table and each row has its one collapse expand icon. here is my code.
Note: I have renamed the variables to hide my data so the code might not work as it is.
function populateInstanceTable(tableData){
// Use to determine whether the child rows for all parents should be shown or hidden.
var SHOW_ALL_CHILDREN_FLAG = false;
var CHILD_DISPLAY_STATE_OVERRIDE = false;
var TABLE = $('#table_instance').DataTable(
{
'aaData': tableData,
'bProcessing': true,
'aoColumns': [
{
'sTitle': 'Column1',
'mData' : 'col1Data'
},
{
'sTitle': 'Column2',
'mData' : 'col2Data'
},
{
'sTitle': 'Column3',
'mData': 'col3Data'
},
{
'class': 'show-details',
'orderable': false,
'data': null,
'defaultContent': ''
}
]
}
);
function getDetailContent(details) {
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td style="border:0px;">More Details:</td>'+
'<td style="text-align:left;max-width:100%;border:0px;">' + details + '</td>' +
'</tr>' +
'</table>';
}
//This function shows and hides multiple child rows with details, for following conditions
// when user clicks '+' or '-' icon
// When user uses search
// when user changes the number of entries per page
// when user navigates through the table
// #remark: With exception of expand all and collapse all events, the display state is retained for child rows
//that have been previously visited. Visited implies the parent row's show or hide details icon was individually clicked.
function collapseOrExpandRows() {
var numberOfVisibleParentRows = $('#table_instance tbody tr td.show-details').length;
for (var i = 0; i < numberOfVisibleParentRows; i++) {
var parentJQRow = $('.show-details').parents('tr').eq(i);
var parentDTRow = TABLE.row(parentJQRow);
// visited_child helps us retain the state of the child row display while
// searching, navigating, sorting or changing number of entries
// We always change the state of child if collapse all(- icon) or expand all(+ icon) is clicked.
if (parentJQRow.hasClass('visited_child') === false || CHILD_DISPLAY_STATE_OVERRIDE === true) {
if (SHOW_ALL_CHILDREN_FLAG === true) {
// We are populating a child row with a table because the parent datatable does not support colspan property.
parentDTRow.child(getDetailContent(parentDTRow.data().details)).show();
parentJQRow.addClass('shown');
}
else {
parentDTRow.child.hide();
parentJQRow.removeClass('shown');
}
}
}
}
//To display details, this event handler shows or hides a single child row
//when the show-details cell is clicked on the parent row
$('#table_instance tbody').on('click', 'td.show-details', function() {
var parentJQRow = $(this).parents('tr');
var parentDTRow = TABLE.row(parentJQRow);
//visited_child helps us retain the state of the child row display while
// searching, navigating, sorting or changing number of entries
parentJQRow.addClass('visited_child');
if (parentDTRow.child.isShown()) {
parentDTRow.child.hide();
parentJQRow.removeClass('shown');
}
else {
parentDTRow.child(getDetailContent(parentDTRow.data().details)).show();
parentJQRow.addClass('shown');
}
CHILD_DISPLAY_STATE_OVERRIDE = false;
});
// This event handler retains the state of the child row display
// when navigating through the table.
$('.dataTables_paginate').on('click', function() {
collapseOrExpandRows();
});
// This event handler hides child row for all visible parents.
$('.collapseall').on('click', function() {
CHILD_DISPLAY_STATE_OVERRIDE = true;
SHOW_ALL_CHILDREN_FLAG = false;
collapseOrExpandRows();
});
// This event handler shows child row of all visible parents.
$('.expandall').on('click', function() {
CHILD_DISPLAY_STATE_OVERRIDE = true;
SHOW_ALL_CHILDREN_FLAG = true;
collapseOrExpandRows();
});
// This event handler retains the state of the child row display
// when the user selects the number of entries to display in the table
$('div.dataTables_length select').on('change', function() {
collapseOrExpandRows();
});
// This event handler retains the state of the child row display
// when the user clicks on header to sort
$('thead > tr > th', '#table_instance').click(function() {
if ($(this).hasClass('show-details') === false) {
collapseOrExpandRows();
}
});
// This event handler retains the state of the child row display
// when the user searches
$('div.dataTables_filter input').keyup(function() {
collapseOrExpandRows();
});
}
I have attached the screenshot for your help.
There is a good example on Datatables Blog having also a wonderful sliding property. There is unfortunately not so much example on the web regarding to this issue, but I hope this example is useful for you.
I know this is an old thread. But I could not find any good examples since then. I created a working example which is fully scalable using jQuery (3.5.0) and Datatables (1.10.19). Table, columns, rows and sub tables are created on the fly based on data structure.
You can find the demo and code here - https://banglaonline.org/dashboard/temp/dt.html. The js code is in https://banglaonline.org/dashboard/temp/dt.js.
function dataStructure() - creates the first table
function dataStructure(){
$("#content_structure").html("<div id='content_structure_table' style='width:80%'></div>");
var groupBy=[fieldOrder[0].field];//level 1 order
var dtTextColumnIndex=[];
var dtNumColumnIndex=[];
var colCount=1;
var valuefunction=null;//dataCreateValueFunctions();
tblFormatParam = formatTblDataStructure('tblDataStructure',0,"1=1");
html = tblFormatParam[0];
tableDef = tblFormatParam[1];
$("#content_structure_table").html(html);
var table = $('#tblDataStructure').DataTable(tableDef);
//drill down event
$('#tblDataStructure tbody').on('click', 'td.details-control', function(){
e=$(this);
drillTblDataStructure(e,table,valuefunction);
});
$('#tblDataStructure' ).bind( 'xhr.dt', function () {
var json = table.ajax.json();
$('#tblDataStructure').unbind( 'xhr.dt');
//structureChart(json.data);
});
}
function drillTblDataStructure - controls the expansion and contraction of nested tables
function drillTblDataStructure(td,table,valuefunction) {
//console.log("td clicked -"+td.attr("datavalue"));
var tr = td.closest('tr');
var row = table.row( tr );
currentFieldOrder = parseInt(td.attr("fieldorder"));
//close all other open rows
tdDrillControls = document.querySelectorAll("td.details-control");
for (var i=0;i<tdDrillControls.length;i++){
tdi= $(tdDrillControls[i]);
tri = tdi.closest("tr");
r = table.row( tri);
if (r.child.isShown() && (tdi.attr("datavalue") != td.attr("datavalue"))) {//second condition is importatnt, otherwise the row will be keep on showing
r.child.hide();
tri.removeClass('shown');
tdi.html('<span class="ui-icon ui-icon-plus"></span>')
}
}
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
td.html('<span class="ui-icon ui-icon-plus"></span>')
}
else {
td.html('<span class="ui-icon ui-icon-minus"></span>')
childFieldOrder = currentFieldOrder +1;
var whereClause = td.attr("whereClause")+" and "+td.attr("datacolumn")+" = '"+td.attr("datavalue")+"'";
var childTableID = childFieldOrder*10+iTableCounter;
tblFormatParam = formatTblDataStructure('tblDataStructure_' + childTableID,childFieldOrder,whereClause);
html = tblFormatParam[0];
tableDef = tblFormatParam[1];
// Open this row
row.child( html ).show();
tr.addClass('shown');
var oInnerTable = $('#tblDataStructure_' + childTableID).DataTable(tableDef);
$('#tblDataStructure_' + childTableID).bind( 'xhr.dt', function () {//table data is loaded via ajax
var json = oInnerTable.ajax.json();
$('#tblDataStructure_' + childTableID).unbind( 'xhr.dt');
});
$('#tblDataStructure_' + childTableID +' tbody').on('click', 'td.details-control', function(){
e=$(this);
drillTblDataStructure(e,oInnerTable,valuefunction);
});
iTableCounter++;
}
}
function formatTblDataStructure - used by the above two functions to create table structure and definition for Datatables
function formatTblDataStructure ( table_id, groupOrder, whereClause) {
var dtTextColumnIndex=[];
var dtNumColumnIndex=[];
var colCount=1;
if(groupOrder<fieldOrder.length-1) //it is not the last item in the order
var tdColumns=[
{ className: 'details-control',
orderable: false,
data: null,
defaultContent: '<span class="ui-icon ui-icon-plus style="cursor:pointer;"></span>'
}
];
else
var tdColumns=[
{ className: '',
orderable: false,
data: null,
defaultContent: ''
}
];
tdColumns.push({data:fieldOrder[groupOrder].field});
html="<table id='"+table_id+"' ><thead><tr><th></th>";
thtml="<tr><td></td>";
html+="<th>"+fieldOrder[groupOrder]["dataField"]+"</th>";
thtml+="<td></td>"
dtTextColumnIndex.push(colCount);
colCount++;
var valuefunction=[];
for(f in valueFields){//getting field names from json column names
html+="<th>"+valueFields[f]["dataField"]+"</th>";
thtml+="<td></td>"
dtNumColumnIndex.push(colCount);
colCount++;
txt = valueFields[f].groupFunction+"("+valueFields[f].field+") as `"+valueFields[f].field+"`";
valuefunction.push(txt);
tdColumns.push({data:valueFields[f].field});
}
html+="</tr></thead><tbody>"+thtml+"</tr></tbody></table>";
groupBy=[fieldOrder[groupOrder].field];
var tableDef={
"ajax":{
url: src,
data:{
request:'dataStructure'
,dbid:sessionID
,group:JSON.stringify(groupBy)
,where:whereClause
,value:JSON.stringify(valuefunction)
,dt:"assoc"
}
},
createdRow: function( row, data, dataIndex ) {
$( row ).find('td:eq(0)').attr(
{
'fieldOrder': groupOrder,
'datavalue': data[fieldOrder[groupOrder].field],
'datacolumn': fieldOrder[groupOrder].field,
'whereClause': whereClause
}
);
},
columns: tdColumns,
columnDefs: [
{
targets: dtTextColumnIndex,
className: 'dt-body-left dt-head-left'
},
{
targets: dtNumColumnIndex,
className: 'dt-body-right dt-head-right'
//,"render": function ( data, type, row, meta ) {
// return infGroup.format(data);
//}
}
]
}
return [html,tableDef];
}
In the example, data is retrieved as json via ajax from a php backend. Example json response:
{
"data": [
{ "dash_uploaded_data_text1": "Dept 1", "dash_uploaded_data_numeric1": "3", "dash_uploaded_data_numeric2": "11" },
{ "dash_uploaded_data_text1": "Dept 4", "dash_uploaded_data_numeric1": "4", "dash_uploaded_data_numeric2": "8" }
]
}

Making bootstrap-tags responsive, jquery events lost

I am trying to change this demo:
http://maxwells.github.io/bootstrap-tags.html
into a responsive version in which I can set it to readOnly and remove it from readOnly as I like. This code:
var alltags = ["new tag", "testtag", "tets", "wawa", "wtf", "wtf2"];
$(document).ready(function() {
var tagbox = $('#my-tag-list').tags({
suggestions: alltags
});
var tagenable = true;
$('#my-tag-list').focusout(function() {
if (tagenable) {
tagbox.readOnly = true;
$('#my-tag-list').empty();
tagbox.init();
tagenable = false;
}
});
$('#my-tag-list').click(function() {
if(!tagenable) {
tagbox.readOnly = false;
$('#my-tag-list').empty();
tagbox.init();
tagenable = true;
}
});
});
seems to work fairly well, it makes everything readonly after focusout and editable when I click it. However, the editing does not work since I cannot insert new tags nor delete them (seems to be like event handling was lost or something like that).
I am guessing that emptying the #my-tag-list div is causing this, but I cannot yet find a way to use for instance "detach" instead that removes everything inside (not the element itself) and putting it back in again.
I tried to make a JS Fiddle, but it isn't really working so well yet:
http://jsfiddle.net/tomzooi/cLxz0L06/
The thing that does work is a save of the entire website, which is here:
https://www.dropbox.com/sh/ldbfqjol3pppu2k/AABhuJA4A6j9XTxUKBEzoH6za?dl=0
this link has the unminimized JS of the bootstrap-tags stuff I am using:
https://github.com/maxwells/bootstrap-tags/blob/master/dist/js/bootstrap-tags.js
So far I managed to do this with some modifications of the bootstrap javascript code. I use two different tagbox which I hide and unhide with some click events.
var tagbox = $('#my-tag-list').tags({
suggestions: alltags,
tagData: tmp_tags,
afterAddingTag: function(tag) { tagboxro.addTag(tag); },
afterDeletingTag: function(tag) {tagboxro.removeTag(tag); }
});
var tagboxro = $('#my-tag-listro').tags({
suggestions: alltags,
tagData: tmp_tags,
readOnly: 'true',
tagSize: 'sm',
tagClass: 'btn-info pull-right'
});
$(document).mouseup(function (e) {
var container = $("#my-tag-list");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) { // ... nor a descendant of the container
if (tagsave) {
$("#my-tag-listro").show();
$("#my-tag-list").hide();
var tags = tagbox.getTags();
$.post("%basedir%/save.php", {
editorID:"new_tags",
tags:tags
}, function(data,status){
//alert("Data: " + data + "\nStatus: " + status);
});
tagsave = false;
}
}
});
$('#my-tag-listro').click(function() {
tagsave = true;
//$(".tag-list").toggle();
$("#my-tag-list").show();
$("#my-tag-listro").hide();
});
I had to modify the code of bootstrap-tags.js to allow for this since it normally deletes all of the usefull functions when it is considered readonly in the init function:
if (this.readOnly) {
this.renderReadOnly();
this.removeTag = function(tag) {
if (_this.tagsArray.indexOf(tag) > -1) {
_this.tagsArray.splice(_this.tagsArray.indexOf(tag), 1);
_this.renderReadOnly();
}
return _this;
};
this.removeTagClicked = function() {};
this.removeLastTag = function() {};
this.addTag = function(tag) {
_this.tagsArray.push(tag);
_this.renderReadOnly();
return _this;
};
this.addTagWithContent = function() {};
this.renameTag = function() {};
return this.setPopover = function() {};
}
would be awesome if this feature was incorporated in a somewhat less hacky way though :)

Reusing a modal template

On my current project, there are starting to be a few views that are modal views that are being used to delete items on the site. They are currently generic in that it's just a text description of the item they are deleting. Maybe in the future there will be an icon or a short description as well. There are now tasks to have that functionality to delete other stuff on our site. I'm new to the web, MVC, asp.net, etc, and what I want to know is if it's better to reuse our current modal view somehow, and pass in the objects we need to show in the view. Because the view needs to send the url back to the server on which items to delete, that part of code would need to be different for the view as well. Here is some of the stuff in our view along with a .cshtml template that's pretty generic that I didn't include.
Views.DeleteGiftModal = (function () {
return Backbone.View.extend({
template: Templates["template-gift-delete-modal"],
tagName: 'div',
initialize: function (options) {
$(window).bind("disposeModal", _.bind(this.disposeModal, this));
_.bindAll(this, "showDialog", "disposeModal", "displayResults");
this.eventAggregator = options.eventAggregator;
this.itemsToDelete = options.model;
this.errors = {};
this.render();
return this;
},
events: {
"click #delete-btn": "deleteItems",
"click #ok-btn": "disposeModal",
"click #cancel-btn": "disposeModal"
},
disposeModal: function (event, refresh) {
this.$el.modal("hide");
if (event != null && event.currentTarget != null && event.currentTarget.id == 'ok-btn')
refresh = true;
this.trigger("modalClosed", refresh);
this.remove();
this.unbind();
},
showDialog: function () {
this.$el.modal("show");
},
deleteItems: function () {
var self = this;
var element = this.$el;
var numberGifts = this.getKeys(this.itemsToDelete).length;
this.results = [];
var hasError = false;
element.find("#actions").hide();
element.find("#ok-actions").show();
$.each(this.itemsToDelete, function(i, v) {
// tell model to go away
var gift = new Gift({ id: i });
gift.destroy({
success: function (model, response) {
self.results.push({ id: model.id, response: response });
numberGifts--;
if (numberGifts <= 0) {
if (!hasError) {
self.disposeModal(null, true);
} else {
self.displayResults();
}
}
}
});
});
},
displayResults: function () {
var element = this.$el;
$.each(this.results, function(i, v) {
// to do check response for error message
var list = element.find("#delete-item-" + v.id);
if (v.response.message == "Deleted") {
list.append(" - <span align='right' style='color: green'>Deleted</span>");
} else {
hasError = true;
list.append(" - <span align='right' style='color: red'>" + v.response.message + "</span>");
}
});
},
render: function () {
this.$el.append(this.template);
this.$el.find("#ok-actions").hide();
// show list of item names
var list = this.$el.find("#items-to-delete-list");
$.each(this.itemsToDelete, function (i, v) {
$("<li id='delete-item-" + i + "'>" + v.name + "</li>").appendTo(list);
});
this.$el.attr('id', 'delete-gift-dialog');
return this;
}
});
})();
As I am looking through the code, and this being my first real project, it seems like a lot of things that could be quite similar, like deleting a Gift, deleting a Toy, etc have different Controllers for each (GiftController, ToyController), and hit different URLs. So currently things are all in their own class like that. I was wondering if that's the more standard way to approach these types of problems as well with views. Thanks in advance!
The app we're developing at work had a similar issue. We're using Backbone too so I can completely relate to this. What I ended up doing is have a sort of ModalBuilder that builds a form in a modal for you and binds events on the form elements for submit. The initialization of it could look like this:
new ModalBuilder({
form: [
{
tag: 'select[name="id"]',
options: [
{ name: 'Item 1', id: 12 },
{ name: 'Item 2', id: 32 }
]
},
{
tag: 'input[type="submit"]',
value: 'Delete'
}
],
events: function(){
$('input[type="submit"]').on('click', function(){
// Delete via ajax
})
}
})
What we do is we have different templates for every form element, inputfields and textareas and so on and we reuse it all over the place. ModalBuilder takes these arguments and builds a form
Also for certain cases it might be better to render the form server-side and deliver it to your modal via ajax. You have to weigh what makes your app more performant I suppose.

Categories