Suraz Khanal
Suraz Khanal

Reputation: 222

keeping track of the removed indices of an array javascript

i have a form with text box and checkbox. When i fill value to the checkbox , the value is pushed into an array.When I unchecked the checkbox, the value is removed from that array. Here is my working code pen.

This is my form code

<label class="item item-input">
    <input type="text" placeholder="In a word, what is important to you?" ng-model="values.first" >
    <ion-checkbox ng-click="toggleCheckBox(success.first,values.first)"  ng-change="show2='true'" ng-model="success.first"  
           ng-disabled="!values.first" style="border: none;padding-left: 30px;" class="checkbox-royal"></ion-checkbox>
  </label>

  <label class="item item-input" ng-show="show2" ng-class="{'animated-custom slideInLeft':success.first}">
    <input type="text" placeholder="What else is important to you?" ng-model="values.second" >

    <ion-checkbox class="checkbox-royal" ng-model="success.second" ng-click="toggleCheckBox(success.second,values.second)" ng-change="show3='true'" ng-disabled="!values.second" style="border: none;padding-left: 30px;"></ion-checkbox>
  </label>

  <label class="item item-input" ng-show="show3" ng-class="{'animated-custom slideInLeft':success.second}">
    <input type="text" placeholder="What else is important to you?" ng-model="values.third">

    <ion-checkbox class="checkbox-royal" ng-model="success.third" ng-click="toggleCheckBox(success.third,values.third)" ng-change="show4='true'" ng-disabled="!values.third" style="border: none;padding-left: 30px;"></ion-checkbox>
  </label>

  <label class="item item-input" ng-show="show4" ng-class="{'animated-custom slideInLeft':success.third}">
    <input type="text" placeholder="What else is important to you?" ng-model="values.four">

    <ion-checkbox class="checkbox-royal" ng-model="success.four" ng-click="toggleCheckBox(success.four,values.four)" ng-change="show5='true'" ng-disabled="!values.four" style="border: none;padding-left: 30px;"></ion-checkbox>
  </label>

And this is controller code ,

.controller('myctrl',function($scope){
  var values=[];
  $scope.toggleCheckBox=function(isChecked, value){
    if(isChecked){
      values.push(value);
      console.log(values);
    }else{
      var currentIndex = values.indexOf(value);
      values.splice(currentIndex, 1);
      console.log(values);
       //console.log(values.indexOf(value));
    }
  }
})

The problem is, when i remove the value from array and again check the checkbox, it pushes the value to last . Is it possible to retain the original position of that value in the array?

Upvotes: 1

Views: 87

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

JavaScript Object properties order never change

So, you can create an Object to maintain the order and iterate over the Object.keys() to fill the array values based on the value or false accordangly:

angular
  .module('ionicApp', ['ionic'])
  .controller('myctrl', function ($scope) {
    var values = [],
        obj = {};

    $scope.toggleCheckBox = function (isChecked, value, index) {
        values = []; // Clean the values
        obj[index] = (isChecked) ? value : false;
        Object.keys(obj).forEach(function (k) {
            obj[k] && values.push(obj[k]); // Fill the ordered values
        });

        console.clear();
        console.log(values);
    };
  });

In the veiew, I have added an index for all the checkboxes, which is the number of the ion-checkbox:

<ion-checkbox 
  ng-click="toggleCheckBox(success.first,values.first, 1)"  
  ng-change="show2='true'" 
  ng-model="success.first"
  ng-disabled="!values.first" 
  style="border: none;padding-left: 30px;"
  class="checkbox-royal">
</ion-checkbox>

Check the complete solution at Code Pen.

Upvotes: 1

Phortuin
Phortuin

Reputation: 770

In theory, you can add a value to a specific index in an array:

let arr = ['foo', 'bar'];
arr[3] = 'baz'; // 0 and 1 are taken
console.log(arr); //=> ['foo', 'bar', undefined, 'baz']

This is not recommended however. In JavaScript, arrays are numbered indexes and trying to work around this behaviour will likely become problematic very soon.

What you need instead is an object. If you name your inputs:

<input name="some_checkbox_1">

...and use those names to create an object:

$scope.toggleCheckBox=function(isChecked, value){
    values[this.name] = isChecked;
}

Which results in an object like this:

{ some_checkbox_1: true, some_checkbox_2: false } // this is the `values` variable

If you then want to get an array out of this object with the true and/or false values, use Object.values():

Object.values(values); //=> [true, false]

This way, you can render your checkboxes in sequence and set them to checked based on the true/false values of your stored object. Hope this helps.

Note: in the code above I assume that this refers to the checkbox’s HTML element

Upvotes: 1

gus27
gus27

Reputation: 2666

Add a third parameter to toggleCheckBox with the position - something like:

...
<ion-checkbox class="checkbox-royal" ng-model="success.four" ng-click="toggleCheckBox(success.four,values.four,4)"
...

and in your controller:

.controller('myctrl',function($scope){
  var values=[];
  $scope.toggleCheckBox=function(isChecked, value, pos){
    if(isChecked){
      values[pos] = value;
    }else{
      values[pos] = null;
    }
    console.log(values);
  }
})

Upvotes: 1

Dabbas
Dabbas

Reputation: 3230

Pass the item index in toggleCheckBox and set the value of the array item depending on the passed index and the values you want like:

var x = Array();
var index = 2;
x[index] = 'A';
console.log(x);

But make sure when you want to use the array to iterate over it and splice the items with undefined values.

Upvotes: 1

Related Questions