Yolanda
Yolanda

Reputation: 3

Excluding an undefined value

Every once in a while I will see an <li>undefined</li> How do i get it to not loop over the undefined <li>?

function relatedCoursesMesh() {
    if ($('#relatedCourses').length != 0) {
        var courseNumber = $.parseHTML($('#relatedCourses #RelatedCourseNumber').html()),
            courseName = $.parseHTML($('#relatedCourses #RelatedCourseName').html()),
            parsedCourseNumber = courseNumber[0].data.split("+"),
            parsedCourseName = courseName[0].data.split("+");


        htmlOutput = "<ul>";

        $(parsedCourseNumber).each(function (index, val) {

            htmlOutput += '<li><a data-course="' + val + '" data-title="' + parsedCourseName[index] + '" href="/Pages/Class.aspx?course=' + val + '&courseTitle=' + parsedCourseName[index] + '" title="Related Course">' + parsedCourseName[index] + '</a></li>';
        })
        htmlOutput += "</ul>";
        $('#relatedCourses').html(htmlOutput);
    }
} 

Upvotes: 0

Views: 54

Answers (2)

You can control if the value of val variable return as undefined, so:

function relatedCoursesMesh() {
    if ($('#relatedCourses').length != 0) {
        var courseNumber = $.parseHTML($('#relatedCourses #RelatedCourseNumber').html()),
            courseName = $.parseHTML($('#relatedCourses #RelatedCourseName').html()),
            parsedCourseNumber = courseNumber[0].data.split("+"),
            parsedCourseName = courseName[0].data.split("+");


        htmlOutput = "<ul>";

        $(parsedCourseNumber).each(function (index, val) {
            if(val !== undefined && parsedCourseName[index] !== undefined) {
              htmlOutput += '<li><a data-course="' + val + '" data-title="' + parsedCourseName[index] + '" href="/Pages/Class.aspx?course=' + val + '&courseTitle=' + parsedCourseName[index] + '" title="Related Course">' + parsedCourseName[index] + '</a></li>';
            }
        });
        htmlOutput += "</ul>";
        return $('#relatedCourses').html(htmlOutput);
    }
} 

Being a function it would be better to return the value of the operation performed:

return $('#relatedCourses').html(htmlOutput);.

But surely the best way is to see why the data is originally defective.

Upvotes: 0

Cody Geisler
Cody Geisler

Reputation: 8617

You can put an if statement like so:

    $(parsedCourseNumber).each(function (index, val) {
        if(parsedCourseName[index]) { // also ignores "" (blank) and null values
            htmlOutput += '<li><a data-course="' + val + '" data-title="' + parsedCourseName[index] + '" href="/Pages/Class.aspx?course=' + val + '&courseTitle=' + parsedCourseName[index] + '" title="Related Course">' + parsedCourseName[index] + '</a></li>';
        }
    })

Upvotes: 2

Related Questions