Gibs LeFleur
Gibs LeFleur

Reputation: 131

Javascript loop doesn't work in meteor

This should work but its not. What am I doing wrong? I want to output "selected" to tags I have on a meteor page

Template.editor.onRendered( function() {
var cats = ["Comedy","Action","Self Help"];
var arrayLength = cats.length;
for (var i = 0; i < arrayLength; i++) {
    if(cats[i].indexOf(getDocument.category) != -1){
        //found
        var id = cats[i].trim().toLowerCase();
        $("body").find("#"+id).attr("selected=selected");
        console.log(id);
    } else {
        console.log(getDocument.category)
    }
}
}

also

getDocument.category = ["Action", "Comedy"]

Upvotes: 1

Views: 90

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

You need to change a line to set selected attribute

$("body").find("#"+id).attr("selected","selected");

Or try the following:

$(document).find("#"+id).attr("selected","selected");

Upvotes: 0

Erdiansyah
Erdiansyah

Reputation: 101

If I do not mistakenly understand what you asking for, you are trying to find the elements of 'cats' array if exist in the getDocument.category. If so, the above approach is wrong. Take a look at this line:

if(cats[i].indexOf(getDocument.category) != -1){...}

the result of this if checking will always returning -1, the explanation is below:

cats[i] will return the element (with index i) of cats, so if i=0 the result will be "Comedy". Then, indexOf will be executed on it, "Comedy".indexOf() , to find the position of getDocument.category (which is an array).

That's means you are looking for an array inside a string? that's will not work.

Actually, we can check if an element exists in array with includes methods. So maybe the complete code will be looked like this:

Template.editor.onRendered(function() {
    var cats = ["Comedy", "Action", "Self Help"];
    var arrayLength = cats.length;
    for (var i = 0; i < arrayLength; i++) {
        if (getDocument.category.includes(cats[0])) {
            //found
            var id = cats[i].trim().toLowerCase();
            $("body").find("#" + id).attr("selected=selected");
            console.log(id);
        } else {
            console.log(getDocument.category)
        }
    }
})

Hope this will help, thanks

Upvotes: 0

schaffioverflow
schaffioverflow

Reputation: 510

Maybe change

$("body").find("#"+id).attr("selected=selected");

with

$("body").find("#"+id).attr("selected","selected");

Edit:

if(cats[i].indexOf(getDocument.category) != -1){

I think you have here a wrong direction try this instead:

if(getDocument.category.indexOf(cats[i]) != -1){

Upvotes: 3

Related Questions