Reputation: 15293
I am doing a DOM manipulation using jQuery's map
function. Using this I am trying to append an element to a form.
It works fine only one time; by that mean I am getting the result only in the if
portion, I can't get any value from the else if
portion. What is wrong with my function, or is my approachwrong?
My data:
"fields":[
{
"id":"firstname",
"label":"First Name",
"name":"fname",
"type":"text",
"value":""
},
{
"id":"email",
"label":"Email",
"name":"email",
"type":"text",
"value":""
},
{
"id":"countries",
"label":"Country",
"name":"countries",
"type":"select",
"options":[
{
"value":"",
"text":"Select Country"
},
{
"value":"in",
"text":"India",
"selected":"true"
},
{
"value":"us",
"text":"United Stated"
},
{
"value":"uk",
"text":"United Kingdom"
},
{
"value":"cn",
"text":"Canada"
}
]
},
{
"id":"submit",
"name":"submit",
"type":"submit",
"value":"Submit"
}
]
My function:
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.id) {
console.log(val.id); // getting values and appending elements
}
if (val.label) {
element = $('<label />',{text:val.label}); // am not getting any value here..
}
if (val.type) {
element = $('<input />',{id:val.id}) // I am only getting value here..
}
} )
)
: ""));
} )
}
What is the issue? Can anyone help me?
Upvotes: 0
Views: 145
Reputation: 15101
Your code works as expected, your would not get to the else part if the first if evaluates to true. Once if(val.id)
returns true all the rest would be skipped
Upvotes: 1
Reputation: 2278
else if
only gets called if the previous if/else if statements weren't. For example:
if (true) {
// This code gets run
}
else if (true) {
// This code never will
}
With that in mind, change your if statements to be like the following:
if(val.id) {
console.log(val.id);
}
if (val.label) {
console.log(val.label);
}
if (val.type) {
console.log(val.type);
}
Upvotes: 1