0

I found and edited this code to use jquery to display elements of an xml feed from an online calendar on a web page. Is there a way for me to include conditions so that I can display the information from a node when it's populated and ignore it when the node is empty? For example, to include the imagepath, imagetext and necessary html to format it but disregard all of that when there is no imagepath and imagetext information?

<script>
$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "http://orion.lib.mi.us/evanced/lib/eventsxml.asp?dm=exml&lib=0&nd=90",
        dataType: "xml",
        success: xmlParser,
        error: function(){alert("We're sorry. Something didn't load correctly.");}
    });
});

function xmlParser(xml) {
    $(xml).find("item").each(function () {
        var xml_image       = $(this).find('imagepath').text();
        var xml_imagetext   = $(this).find('imagetext').text();
        var xml_title       = $(this).find('title').text();
        var xml_date        = $(this).find('date').text();
        var xml_time        = $(this).find('time').text();
        var xml_location    = $(this).find('location').text();
        var xml_link        = $(this).find('link').text();
        var xml_description = $(this).find('description').text();
        $(".main").append('<div class="event"><div class="logo"><img alt="' + xml_imagetext + '" src="' + xml_image + '" /></div><p class="title"><a href="' + xml_link + '">' + xml_title + '</a></p><p class="when">' + xml_date + ' at ' + xml_time + '</p><p class="location">Location: ' + xml_location + '</p><p class="description">' + xml_description + '</p><p class="link"><a href="' + xml_link + '">More Information</a></p></div>');
    });}
</script>

1 Answer 1

1

You might want to simply add a condition before appending the content to main.

if (xml_image != "" && xml_imagetext != "") {
    $(".main").append...
}

Or if you want to display different things, do something along these lines:

var hasImage = xml_image != "" && xml_imagetext != "";
var html = "<div class='event'>" +
    ((hasImage) ? "<img src='" + xml_image + "' alt='" + xml_imagetext + "' />" : "")
    + "</div>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. I thought something like that would work but my attempts always broke the page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.