title: CSS, knockout.js : how to dynamically assign id to checkbox with foreach data-bind
body: <p>I have this code where I am using knockout.js <code>foreach</code> binding with checkboxes styled using images in css classes. </p>
  
  <p>how can I dynamically assign id to each checkbox separately and associate the label to that dynamic checkbox id.</p>
  
  <p>Can anyone help me resolve this?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=checkbox].css-checkbox1 {
    display: none;
    width: 30px;
    margin: 0;
    padding: 0;
    opacity: 0;
  }
  input[type=checkbox].css-checkbox1 + label {
    display: inline-block;
    height: 30px;
    width: 30px;
    line-height: 30px;
    cursor: pointer;
    padding-left: 30px;
    background-repeat: no-repeat;
    background: url(../images/img_sprite.png) no-repeat -14px -78px;
  }
  input[type=checkbox].css-checkbox1:checked + label {
    background: url(../images/img_sprite.png) no-repeat -47px -78px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
  
  &lt;head&gt;
    &lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
    &lt;input type="button" value="Activity" data-bind="click: showActivity" /&gt;
    &lt;div data-bind="if: showActivityMenu"&gt;
      &lt;div data-bind="foreach:activity"&gt;
        &lt;input type="checkbox" id="checkbox1" value=" " data-bind="checkedValue: name, checked:$parent.selectedActivity" class="css-checkbox1" /&gt;
        &lt;label for="checkbox1" data-bind="text:name"&gt;&lt;/label&gt;
      &lt;/div&gt;
      &lt;div style="float:right;"&gt;
        &lt;button data-bind="click:collectActivity"&gt;OK&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div data-bind="ifnot: showActivityMenu"&gt;
      &lt;span class="inner" data-bind="text:selectedActivity"&gt; &lt;/span&gt; 
    &lt;/div&gt;
  &lt;/body&gt;
  
  &lt;script&gt;
    function AAsearchViewModel() {
      var self = this;
      self.showActivityMenu = ko.observable(false);
      self.activity = ko.observableArray([{
        name: 'Yoga',
        val: 1
      }, {
        name: 'Pilates',
        val: 2
      }, {
        name: 'Kickboxing',
        val: 3
      }]);
      self.selectedActivity = ko.observableArray(['Pilates']);
      self.showActivity = function() {
        self.showActivityMenu(true);
      };
      self.collectActivity = function() {
        self.showActivityMenu(false);
      };
    };
  
    ko.applyBindings(new AAsearchViewModel());
  &lt;/script&gt;
  
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>