Search code examples
javascripthtmlformsw2ui

Fill w2ui from with content upon creation


I want to fill the textarea of a form with content when the form is created. I am trying to do it with an onRender event but the field is undefined so its 'value' property cannot be changed.

It can be seen in the snippet below that the Load button is successful in inserting contents into the textarea but the onRender event fails to do it.

$(function () {
    $('#form').w2form({ 
        name  : 'form',
        fields: [
            { field: 'comments',   type: 'textarea'}
        ],
        // Load some content inside text area onRender.
        onRender: function(event) {
            event.onComplete = function () {
                // Option 1: Get from class.
                //document.getElementsByClassName('foo')[0].value = "Fill text" // This does nothing.
                // Option 2: Get from object.
                if (this.fields[0].el != undefined) {
                	this.fields[0].el.value = "Fill text" // This raises error because this.fields[0].el does not exist yet.
                }
            }
        },    
        actions: {
            load: function () {
                // Option 1: Get from class.
                //document.getElementsByClassName('foo')[0].value = "Fill text"
                // Option 2: Get from object.
                this.fields[0].el.value = "Fill text"
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.js"></script>

<div id="form" style="width: 750px;">
    <div class="w2ui-page page-0">
        <div class="w2ui-field">
            <label>Text Area:</label>
            <div>
                <textarea name="comments" class="foo" type="textarea" style="width: 385px; height: 80px; resize: none"></textarea>
            </div>
        </div>
    </div>

    <div class="w2ui-buttons">
        <button class="w2ui-btn" name="load">Load</button>
    </div>
</div>


Solution

  • You can use w2form.record:

    $(function () {
        $('#form').w2form({ 
            name  : 'form',
            fields: [
                { field: 'comments',   type: 'textarea'}
            ],
            record: {
                "comments": "Hello World!"
            }
        });
    });
    

    Fiddle: http://jsfiddle.net/fgfLwbsu/5/