javascriptdojodijit.formdijit.layout

How to add a `HTML label` before a `ValidationTextBox` dynamically?


I need to add dynamically HTML labels before each ValidationTextBox.

ValidationTextBox and HTML label are created accordingly to the number of property present for object data.

I would need an example on how to do it.

Example: http://jsfiddle.net/F2qAN/97/#run

dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.layout.ContentPane");

    function build() {
        var data = {
            name: 'a',
            surname: 'b',
            age: 'c'
        },
        validationTextBox,
        layout = new dijit.layout.ContentPane({});
        Object.keys(data).forEach(function (prop, index) {
            validationTextBox = new dijit.form.ValidationTextBox({
                id: prop + '-'+ index,
                name: prop,
                value: data[prop]
            });
            layout.addChild(validationTextBox);
        }.bind(this))
        layout.placeAt('layout');
        layout.startup();
    }

    dojo.addOnLoad(build);

I am trying using dojo/dom-construct but with no result, ex:

        var label = domConstruct.toDom("<label for="male">label</label>");
        layout.addChild(validationTextBox);
        layout.addChild(label );

Solution

  • Using a home made widget is the proper approach for that.

    require(['dijit/form/ValidationTextBox', 'dijit/layout/ContentPane', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dojo/_base/declare', 'dojo/domReady!'], function(ValidationTextBox, ContentPane, _WidgetBase, _TemplatedMixin, declare, domReady) {
         var data = {
            name: 'a',
            surname: 'b',
            age: 'c'
        },
        layout = new ContentPane(),
        LabelTextbox = declare([_WidgetBase, _TemplatedMixin], {
            label: '',
            textboxId: '',
            name: '',
            value: '',
            
            templateString: '<div><label>${label}</label><div data-dojo-attach-point="textboxNode"></div></div>',
            
            postCreate: function() {
                this.inherited(arguments);
            
                this.own(new ValidationTextBox({
                    id: this.textboxId,
                    name: this.name,
                    value: this.value
                }, this.textboxNode));
            }
        });
    
        Object.keys(data).forEach(function (prop, index) {
            layout.addChild(new LabelTextbox({
                textboxId: prop + '-'+ index,
                name: prop,
                value: data[prop],
                label: 'foo'
            }));
        }.bind(this));
    
        
        layout.placeAt('layout');
        layout.startup();
    
    });
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/claro/claro.css" media="screen">
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
    <div id="layout"></div>