user2492364
user2492364

Reputation: 6693

Javascript: check if for loop value in array

I have 30 users with id 1~30
And the memberInThisGroup is an array [2,24]
And I want to check if the id is in the array(2,24) then give it the option with selected

string +="<option value=\""+data.userId+"\"  selected >"+data.userName+"</option>"; 

else , just a normal option

string +="<option value=\""+data.userId+"\">"+data.userName+"</option>";    

Here is My code with error ,It seems like it just check one time,and the selected option is opposite
Please guide me how to write
thank you

function getCurrentusers(memberInThisGroup,groupId) {
    console.log(memberInThisGroup);  //2,24
    $.ajax({
        type : 'GET',
        url : 'currentusers',
        async : true,
        success : function(datas) {  
                //for loop every elements
                var string ="";
                for(var i in datas){
                    var data = datas[i];    
                    if(memberInThisGroup.indexOf(data.userId)){
                        console.log("We have member"+data.userId);
                        string +="<option value=\""+data.userId+"\"  selected >"+data.userName+"</option>"; 
                    }else{
                        console.log("We don't have member"+data.userId);
                        string +="<option value=\""+data.userId+"\">"+data.userName+"</option>";    
                    }
                }
                $("#e_"+groupId).append(string);    
                $('#e_'+groupId).multiSelect('refresh');            

        }
    });
}

datas ajax get is json like:

[{"userId":1,"userName":"Ken","password":"a12345","account":"[email protected]"},
{"userId":2,"userName":"wen","password":"qqqq","account":"[email protected]"},
{"userId":3,"userName":"win","password":"1234","account":"[email protected]"},...]

Here is my console output:

We have member1
We don't have member2
We have member3
We have member4
We have member5
.... 

But what I expect is :

We have member2
We have member24
We don't have member1
We don't have member3
We don't have member4
We don't have member5
....

Upvotes: 0

Views: 88

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this

var string = "",
    memberInThisGroup = [2, 24], // just for test 
    data, selected;

for (var i = 0, len = datas.length; i < len; i++) {
    data     = datas[i];
    selected = (memberInThisGroup.indexOf(data.userId) >= 0) ? 'selected' : '';

    string += "<option value=\"" + data.userId + "\" " + selected + ">" + data.userName + "</option>"; 
}

Example

Upvotes: 1

Related Questions