jeudi 4 avril 2019

JavaScript: how to append paragraph if situation is not filled?

I'm working on a simple project that checks to see if a student is working on an online journal. The student's progress is checked with a userId. If the student's userId does not appear in the JSON returned by an API call to the class API, a paragraph should be appended to a container to tell the student they have not completed anything.

Here's an example of the type of data I'm working with.

data = [ {"userId": 101,
pagesDone: "005"},
{"userId": 102,
pagesDone: "010"},
{"userId": 103,
pagesDone: "020"},
{"userId": 104,
pagesDone: "015"} ]

Now let's say that I'm working with a student with a userId of 106. This student doesn't appear in the JSON data because they haven't started working on the journal.

let currentUserId = 106;
//student has not completed anything in their journal

let showStudentJournal = (data, currentUserId) => {

    for (var index = 0; index < data.length; index++) {
        if (currentUserId == data[index].userId) {

    //I have figured out the code here, basically I append a progressBar to a container to show the student's progress
//I won't show the code here since that's not what we're focusing on. 

            //the thing I want to happen is, get a paragraph to appear if the student hasn't filled out any of the online journal yet
            else {
                $("#progressContainer").append('<p>You have not yet started your online Journal</p>');
            }
        }
    }

    }

However, the function ends up running 4 times (because there are 4 students in the data). So this is what I get back:

'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'

How do I get the error message to only appear once?

Aucun commentaire:

Enregistrer un commentaire