J. Davidson
J. Davidson

Reputation: 3307

Selecting a dropdown option from a for loop

I have following for loop. Which sees if the data value is in the dropdown if so it will show it as selected.

for (var i in data) {
    $("#optionDropdwon option:contains(data[i])").prop("selected", true);
    console.log(data[i])
}

It works fine when I replace data[i] in the :contains() with an actual string i.e "xyz" but when I replace it with data[i] nothing happens. Yet I can see console.log(data[i]) shows me the proper values. I searched Stackoverflow but couldn't find something like what I am doing.

Please let me know where I am making a mistake. Thanks

Upvotes: 0

Views: 52

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74038

You must construct a proper selector for this to work. In your example, you have only the literal string data[i] in the selector, but not the actual value

$("#optionDropdwon option:contains(" + data[i] + ")").prop("selected", true);

Upvotes: 1

Related Questions