Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving state of checkboxes generated by Rxjs

Tags:

rxjs5

Based on selecting different items in a dropdown, I am generating html of items with check boxes. How can I preserve the state of checkbox i.e. check/uncheck whenever value in dropdown is changing. See the plunkr here https://plnkr.co/edit/PUG3g7dfTbQjPyIgGLzh?p=preview

Steps:

- uncheck 'abc2'
- change dd value to 'international'
- again change the dd value to 'local'
- here 'abc2' must be unchecked...

here is my code:

var data = [
    {type: 'local', name: 'abc1', location: 'xyz1', checked: true},
    {type: 'local', name: 'abc2', location: 'xyz2', checked: true},
    {type: 'international', name: 'abc3', location: 'xyz3', checked: true},
    {type: 'local', name: 'abc4', location: 'xyz4', checked: true},
    {type: 'local', name: 'abc5', location: 'xyz5', checked: true},
    {type: 'international', name: 'abc6', location: 'xyz6', checked: true},
    {type: 'international', name: 'abc7', location: 'xyz7', checked: true}
];

var $container = $('#container');
var $splitDD = $('#testDD');
var splitDD$ = Rx.Observable.fromEvent($splitDD, 'change')
    .startWith($splitDD.val())
    .map(function(e) { $container.html(''); return e.target ? e.target.value : e;})
    .switchMap(function(v) {return data;})
    .filter(function(v) {
      return v.type == $splitDD.val()
    })
    .map(getHtml)
    .subscribe(function(html) {
            $container.append(html);
    });


function getHtml(v) {
    var checked = v.checked ? 'checked="checked"' : '';
    var html = '<label><input class="point" name="' + v.name + '" type="checkbox" ' + checked + '>' +
        '<span>' + v.name + ' </span>' +
        '</label>';
    return html;
}
like image 741
coure2011 Avatar asked Nov 09 '22 10:11

coure2011


1 Answers

Here is solved: https://plnkr.co/edit/72ciT20saCpLCLFNBbGv?p=preview


Steps:

added onclick listener to checkbox and while checkbox is changed, array is being updated.

1) in getHTML()

var html = '<label><input onclick="CheckboxPreserve(this);"   ......

2) added in bottom of scripts.js :

function CheckboxPreserve(el){
  var $this = $(el);
  for (var key in data) {
      if (data[key]['name']==$this.attr("name")) {
          data[key]['checked']=$this.is(':checked');
      } 
  }
}
like image 151
T.Todua Avatar answered Dec 01 '22 00:12

T.Todua