Search code examples
javascriptjquerycheckbox2-way-object-databindingjsviews

JsViews Checkbox binding from an inner loop


I am trying to get a two way binding for a checkbox in an inner loop using JsViews

Not sure if this is possible.

<div id="targetSelection"></div>
<script id="targetItem" type="text/x-jsrender">
  <b>{^{:text}}</b>
  <div id="answers_{^{:fieldName}}" class='collapse'>
    {^{for answers ~fieldName=fieldName}}
    <label>
      <input type="checkbox" data-fieldName="{{>~fieldName}}" data-index="{{:index}}" data-link="{:selected}" checked="{^{:selected}}" /> {{:text}} : {^{:selected}}
    </label>
    <br /> {{/for}}
  </div>
  <br />
</script>

and the JS code:

var target = [{
  "fieldName": "GENDER",
  "text": "Gender",
  "answers": [{
    "index": 1,
    "text": "Male"
  }, {
    "index": 2,
    "text": "Female"
  }, ]
}, {
  "fieldName": "AGE",
  "text": "Age",
  "answers": [{
    "index": 1,
    "text": "15-19"
  }, {
    "index": 2,
    "text": "20-24"
  }, {
    "index": 3,
    "text": "25-29"
  }, {
    "index": 4,
    "text": "30-34"
  }, {
    "index": 5,
    "text": "35-39"
  }, {
    "index": 6,
    "text": "40-44"
  }, {
    "index": 7,
    "text": "45+"
  }, ]
}];

$.each(target, function(questionIndex, question) {
  $.each(question.answers, function(answerIndex, answer) {
    answer.selected = true;
  });
});

$("#targetSelection").html($.templates("#targetItem").render(target));

http://jsfiddle.net/22q7z9n9/

I am also trying to fire an event when the checkbox is changed

Thanks in advance


Solution

  • Did you check the JsViews docs? You are calling the render() method, not the link() method, and are using jsrender.js not jsviews.js!

    So you need to load jsviews.js as in Example page, and then write: $.templates("#targetItem").link("#targetSelection", target);

    See http://www.jsviews.com/#jsv-quickstart

    Once you have read the basics, you can continue along the lines of:

    {^{for answers}}
      <label>
        <input type="checkbox" data-link="selected" />
        {{:text}} : {^{:selected}}
      </label>
      <br />
    {{/for}}
    

    For the event, there are a few options including to bind directly to the input change event, or listen to observable changes in your data etc. (http://www.jsviews.com/#observe). See the examples...

    Here is a working version http://jsfiddle.net/28Lezc9m/4/.

    I also changed: <div id="answers_{^{:fieldName}}" class='collapse'> to <div data-link="id{:'answers_ + fieldName" class='collapse'> - as explained in this tutorial sequence.