2

I am building a form dynamically from json using jQuery, and I want to add input fields to my form (e.g. Name, Age, Address, Email).

Here is my code so far:

$(function () { 
//Form JSON
var _form=
{
    "sample_form":
    {
        'Title': 'Form using Jquery/JSON',
        'id': 'test_form',
        'action': 'thanks.html',
        'method': 'post',
        'fields':
        [
            {'id':'txtName' , 'caption':'Name' , 'type':'text' , 'required':'true'},
            {'id':'txtNum' , 'caption':'Age' , 'type':'number' , 'required':'false'},
            {'id':'txtAddress' , 'caption':'Address' , 'type':'address' , 'required':'false'},
            {'id':'txtEmail' , 'caption':'Email' , 'type':'email' , 'required':'true'}
        ]
    }
};

//Creating Form

$('div#form2').append(

    //***********************Header*******************
    $('<br/>'),
    $('<span/>').hide(),
    $("<h2/>").text(_form.sample_form.Title),

    //***********************Form*********************
    $('<form/>',
        {
            id: _form.sample_form.id,
            action: _form.sample_form.action,
            method: _form.sample_form.method
        }
    ).append(
        for (var i = 0; i <_form.sample_form.fields.length ; i++)
        {
            $('<input/>',{ type: i.type , required: i.required , id: i.id})
        }           
    )
);});    

fiddle

2 Answers 2

2
  • for should be out of .append(), as @giorgio has already mentioned;
  • inside for, i.type (and others) should replaced with _form.sample_form.fields[i].type.

Updated fiddle.

Changed part of code:

//Creating Formm

var arr = [];
for (var i = 0; i <_form.sample_form.fields.length ; i++)
{
    var element = _form.sample_form.fields[i];
    arr.push($('<input/>',{ type: element.type , required: element.required , id: element.id}));
}

$('div#form2').append(

    //***********************Header*******************
    $('<br/>'),
    $('<span/>').hide(),
    $("<h2/>").text(_form.sample_form.Title),

    //***********************Form*********************

    $('<form/>',
        {
            id: _form.sample_form.id,
            action: _form.sample_form.action,
            method: _form.sample_form.method
        }
    ).append(arr)
);

});

Sign up to request clarification or add additional context in comments.

Comments

0

You have added a for-loop as a parameter of the append function. You should get it out, and append on each iteration. Example:

var myForm = $('<form/>');
for(var i = 0; i <_form.sample_form.fields.length ; i++)
{
    myForm.append('<input/', { /* paramaters */ });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.