Problema de adición de jquery con función condicional de elementos múltiples

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

gracias por adelantado.

preguntado el 24 de agosto de 12 a las 07:08

2 Respuestas

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

cambia esto

$.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;
} )

a

$.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;
} )

Respondido 24 ago 12, 08:08

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

Respondido 24 ago 12, 07:08

in case if i console the data, i am getting all datas - 3gwebtren

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.