2

Is there a way to check if an array contains a certain value, using knockoutJS, within my HTML?

I have the following checkbox:

<td><input type="checkbox" name="group" data-bind="checked: $parent.name in groupList" /></td>

It would be nice if a certain statement inside my data-bind attribute ($parent.name in groupList) would work, but obviously it doesn't. With twig it's easy:

{% if myVar is in_array(array_keys(someOtherArray)) %}

But I cannot find a way to do this with Knockout JS. groupList contains an array with names and I would like to check if it contains a certain name. If it does, the checkbox needs to be checked, else not.

3
  • 5
    data-bind="checked: groupList().indexOf(ko.unwrap($parent.name)) !== -1" Commented Sep 13, 2016 at 13:21
  • Works perfectly! Thank you for your quick response! Commented Sep 13, 2016 at 13:25
  • @TSV, Nice solution. No need to invoke groupList though. Knockout already provide an indexOf method that is unwrapping the value internally. So, groupList.indexOf(...) will do as well. Commented Sep 13, 2016 at 13:26

1 Answer 1

4

You can use indexOf of an observable array:

data-bind="checked: groupList().indexOf(ko.unwrap($parent.name)) !== -1"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.