0

I am mapping a object, and appending the elements from the object, while i map the elements i am checking the object value and appending the elements appropriately. in my function all are correct i believe, but the last 'if' condition only appending the element, rest of the condition not appending any thing... what would be the fix for this?

var processModules = function (mData) {
    $.map(mData, function (val,i) {
        $(val.container).append(
            $(val.type === 'content' || val.type === 'navigation' ?
            $('<div />',{
                'class':val.attributes['class'],
                id:val.attributes.id})
            .append(val.title ? $('<h2 />',{text:val.title}) : "")
            .append(val.subtitle ? $('<h3>',{text:val.subtitle}) : "")
            :
            val.type === 'form' ? $('<form />',{
                id:val.attributes.id,
                'class':val.attributes['class'],
                action:val.action,
                name:val.name
            })
            .append($('<legend />',{text:val.title}))
            .append(
                $.map(val.fields, function (val,i) {
                    var element;
                    if (val.label) {
                        element = $('<label />',{text:val.label}); // it is not appending
                    }
                    if (val.type) {
                        element = $('<input />',{id:val.id}) // only this is appending, if i place anything after this, only the last condition appends.. any what is the issue? pls check my json tree in the jsfiddle.
                    }
                    return element;
                } )
            )
            : ""));
    } )
}

jsfiddle here for json

thanks in advance.

2 Answers 2

1

make an array of elements. push your element in that array and return that array in append.

change this

$.map(val.fields, function (val,i) {
    var element;
    if (val.label) {
        element = $('<label />',{text:val.label}); 
    }
    if (val.type) {
        element = $('<input />',{id:val.id}) 
    }
    return element;
} )

to

$.map(val.fields, function (val,i) {
   var elements = [];
    var element;
    if (val.label) {
        element = $('<label />',{text:val.label}); 
        elements.push(element); 
    }
    if (val.type) {
        element = $('<input />',{id:val.id}) 
        elements.push(element);
    }
    return elements;
} )
0

looks like you are overwriting element in every if condition. that`s why only the last condition counts.

1
  • in case if i console the data, i am getting all datas
    – 3gwebtrain
    Aug 24, 2012 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.