4

I have a form created via javascript that will be set as the content of a modal widget provided by Alloy UI. However I don't feel I am approaching this the right way. This question applies for javascript-created HTML in general.

I realize I should avoid using global variables for the sake of namespace and collision, so maybe someone can help me out. I declare the global var myForm and initialize it with some HTML elements to create a form:

var myForm = '<form id="my-form" method="get"> 
<div> 
  <select> 
    <option value="option-1">Option 1</option> 
    <option value="option-2">Option 2</option> 
    <option value="option-3">Option 3</option> 
  </select> 
</div> 
</form>'

And a modal widget that sets myForm as the body content:

var modal = new Y.Modal(
    {
        bodyContent: myForm,
        centered: true,
        modal: true,
        resizable: false,
        draggable: false,
        width: 350
    }).render();

This seems like a not-so-great way of using Javascript to render HTML, especially for my project since I will have many html elements created via javascript (<img>'s, <ul>'s etc), so I don't want to get into a bad coding habit. Is there a more standard or acceptable way to dynamically render HTML (not speaking from a templating perspective, i.e., Thymeleaf, etc)? Thanks all

stiemannkj1
  • 3,802
  • 3
  • 21
  • 42
Kurai Bankusu
  • 3,821
  • 11
  • 56
  • 114

2 Answers2

3

An alternative solution is to specify the modal and it's contents in your html, and then let AlloyUI take over and turn it into a modal dialog. You can do this by specifying the boundingBox and contentBox of the Modal as the divs which contain the html you want inside the modal:

YUI().use('aui-modal', function(Y) {
  new Y.Modal({
    boundingBox: '#bb',
    contentBox: '#cb',
    centered: true,
    modal: true,
    resizable: false,
    draggable: false,
    width: 350
  }).render();
});
<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet" />
<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
<div id="bb">
  <div id="cb">
    <form id="my-form" method="get">
      <div>
        <select>
          <option value="option-1">Option 1</option>
          <option value="option-2">Option 2</option>
          <option value="option-3">Option 3</option>
        </select>
      </div>
    </form>
  </div>
</div>
stiemannkj1
  • 3,802
  • 3
  • 21
  • 42
1

I would go with declaring the template inside a script tag as described here: Explanation of <script type = "text/template"> ... </script>

Community
  • 1
  • 1
Shlomi Schwartz
  • 11,238
  • 25
  • 93
  • 155