From 6b13f3527a2e0ef4e15d59450677a532f0e2e2cb Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Thu, 16 Mar 2017 17:01:49 +0100 Subject: [PATCH] Refactoring of duplicate JS form code --- resource/web/event_config.tmpl | 43 +----------------------------- resource/web/js/hal.js | 47 ++++++++++++++++++++++++++++++++- resource/web/sensor_config.tmpl | 47 +-------------------------------- resource/web/trigger.tmpl | 47 ++------------------------------- 4 files changed, 50 insertions(+), 134 deletions(-) diff --git a/resource/web/event_config.tmpl b/resource/web/event_config.tmpl index b73df495..b8a71696 100755 --- a/resource/web/event_config.tmpl +++ b/resource/web/event_config.tmpl @@ -89,49 +89,8 @@ diff --git a/resource/web/js/hal.js b/resource/web/js/hal.js index 61d9dfd5..6da6657b 100755 --- a/resource/web/js/hal.js +++ b/resource/web/js/hal.js @@ -5,7 +5,7 @@ $(function(){ $(".timestamp").relTimestamp(); }); -////////////////////////////////////// JQuery functions +////////////////////////////////////// JQuery helper functions // $.attr() # returns all attributes of an element (function(old) { @@ -121,4 +121,49 @@ function getChartData(json){ axes: dataYaxis, unload: true, }; +} + +////////////// Dynamic forms +var dynamicConf = {}; + +function initDynamicModalForm(modalId, formTemplateId, templateID){ + // read in all configurations into global variable (to skip naming issues) + dynamicConf[formTemplateId] = []; + $("#"+templateID+" div").each(function(){ + dynamicConf[formTemplateId][$(this).attr("id")] = $(this).html(); + }); + // Update dynamic inputs + $("#"+modalId+" select[name=type]").change(function(){ + $("#"+modalId+" #"+formTemplateId).html(dynamicConf[formTemplateId][$(this).val()]); + }); + // click event + $("#"+modalId).on('show.bs.modal', function (event) { + var button = $(event.relatedTarget); + var modal = $(this); + // Reset all inputs + modal.find("#"+formTemplateId).empty(); // clear form div + + // select dynamic form + var selector = modal.find("select[name=type]"); + selector.val(button.data("type")); + selector.change(); // Update dynamic inputs + // set dynamic form data + $.each(button.attr(), function(fieldName, value) { + if(fieldName.startsWith("data-")) { + fieldName = fieldName.substring(5); + // case insensitive search + input = modal.find("input").filter(function() { + return this.name.toLowerCase() == fieldName; + }); + if (input.attr("type") == "checkbox") { // special handling for checkboxes + if (value=="true") input.attr("checked", "true"); + else input.removeAttr("checked"); + // Add default false value as a unchecked checkbox is not included in the post + input.parent().prepend(""); + } else { + input.val(value); + } + } + }); + }); } \ No newline at end of file diff --git a/resource/web/sensor_config.tmpl b/resource/web/sensor_config.tmpl index 807c06a0..f5de4ca9 100755 --- a/resource/web/sensor_config.tmpl +++ b/resource/web/sensor_config.tmpl @@ -194,53 +194,8 @@