Tony33 Tony33 - 2 months ago 12
Ajax Question

ajax append something if condition is verified

How do i make this working?

var makePage = $('<div />').attr('data-role', 'page').attr('id', 'p'+item.id)
.append($('<div>').attr('data-role', 'header')
.append('<a href="#"></a>')
.append('<img src="images/app/logo.png" id="navImg"/>')
.append('<div class="separatore"></div></div>'))
.append($('<div />').attr('data-role', 'main').attr('class', 'ui-content')
.append('<h2 class="hstyle">'+item.name+' '+item.surname+'</h2>')
.append($('<ul />').attr('data-role', 'listview').attr('data-inset', 'true')
if (item.cellulare != '') { .append('<li><a href="tel:+39'+item.cellulare+'"><img src="images/app/tel.png" class="ui-li-icon">'+item.cellulare+'</a></li>') }
) // data-role page
); // data-role main

makePage.appendTo($.mobile.pageContainer);


the condition i want is "if variable item is not empty, append this..".

Thanks

Answer

Store your new div into a variable if you want to later append new elements onto it. The way you were doing it you were telling the compiler to use the append method of a true value which doesn't exist.

var newDiv = $('<div />').attr('data-role', 'page')
                         .append($('<div>')
                         .attr('data-role', 'header');

if (item != '') {
 newDiv.append('<a href="#"></a>')
        .append('<img src="images/app/logo.png" id="navImg"/>');
}

If you need to append into specific elements you need to append at that level then put that level into the parent. For instance if you were trying to append the image inside the anchor (note your code if it were to be proper code would append all into the first div you created):

$('<a href="#"></a>').append('<img src="images/app/logo.png" id="navImg"/>').appendTo(newDiv);

In your first part it looks like you possibly were intending to create a div and then append another div with a specific data-role, but the way you were doing it would create a div with data-role page, append another div, and then update the parent div's data-role to header. To do it in order you should do:

var newDiv = $('<div />').attr('data-role', 'page');
$('<div>').attr('data-role', 'header').appendTo(newDiv);