简体   繁体   中英

Removing a value from array with pure javascript

I realize this may have been asked before in different ways, but I have yet to find an answer that is suitable for this particular situation as it needs to be written in plain JS (no jQuery). This is a class assignment so there's nothing I can do about that.

Basically I was asked to make a list of checkboxes that when clicked send their associated value to an array, then when clicked again to uncheck the box it should remove said value.

The html for this is

            <div>
              <fieldset class="checks">
                <legend><span>What are your favorite JavaScript libraries/frameworks?</span></legend>
                <input type="checkbox" id="jq" value="jQuery" name="libraries" />
                <label for="jq" id="jqLabel">jQuery</label>
                <input type="checkbox" id="angular" value="AngularJS" name="libraries" />
                <label for="angular" id="angularLabel">AngularJS</label>
                <input type="checkbox" id="node" value="NodeJS" name="libraries" />
                <label for="node" id="nodeLabel">NodeJS</label>
                <input type="checkbox" id="react" value="ReactJS" name="libraries" />
                <label for="react" id="reactLabel">ReactJS</label>
                <input type="checkbox" id="backbone" value="Backbone" name="libraries" />
                <label for="backbone" id="backboneLabel">Backbone</label>
            </fieldset>
            </div>

            <p id="testPara"></p>

and the corresponding javascript I have so far is

// Function for JS library selections
var libraryArray = [];

function libraryQuery(event) {

   if (event === undefined) { // get caller element in IE8
      event = window.event;
   }

   var callerElement = event.target || event.srcElement;
   var libraryName = callerElement.value;
   if (callerElement.checked) {
     libraryArray.push(libraryName);
     document.getElementById("testPara").innerHTML = libraryArray;
   }
   else {
     var listItems = document.querySelectorAll(".checks input");

     for (var i = 0; i < libraryArray.length; i++) {
        if (listItems[i].value === libraryName) {
         // remove element at index i from array
           libraryArray.splice(i, 1);
           document.getElementById("testPara").innerHTML = libraryArray;

        }
     }
   }
}

function createEventListeners() {
  var libraries = document.getElementsByName("libraries");
  if (libraries[0].addEventListener) {
     for (var i = 0; i < libraries.length; i++) {
        libraries[i].addEventListener("change", libraryQuery, false);
     }
  } else if (libraries[0].attachEvent) {
     for (var i = 0; i < libraries.length; i++) {
        libraries[i].attachEvent("onchange", libraryQuery);
     }
  }

}

if (window.addEventListener) {
   window.addEventListener("load", createEventListeners, false);
} else if (window.attachEvent) {
   window.attachEvent("onload", createEventListeners);
}

This format is basically the same as what was used in my textbook for another assignment, which works there, but for some reason is giving me really funky results on this project.

For one it will add to the array no problem, but sometimes it will add multiple copies of the same value after checking, unchecking, then checking again, which is no good.

As for the removal when unchecking boxes, sometimes it works, sometimes it doesn't. Sometimes it removes a totally different value than the one associated with the current checkbox being unchecked.

I believe the problem to be somewhere in this for loop, and more specifically it may be a problem with the if statement within it. But after a ton of tinkering I am just stumped on how to correct the issue (I could also be totally wrong in that the error is somewhere else).

 for (var i = 0; i < libraryArray.length; i++) {
    if (listItems[i].value === libraryName) {
     // remove element at index i from array
       libraryArray.splice(i, 1);
       document.getElementById("testPara").innerHTML = libraryArray;

    }
 }

Any help is truly appreciated. Here is a jsfiddle .

You've complicated this, all you need to do is check if the box is checked, and the value isn't already in the array, then push it to the array, otherwise just remove it based on the index.

function libraryQuery() {
    var libraryName = this.value,
        index       = libraryArray.indexOf(libraryName);

    if (this.checked &&  index === -1 ) {
        libraryArray.push(libraryName);
    } else {
        libraryArray.splice(index, 1);
    }
    document.getElementById("testPara").innerHTML = libraryArray;
}

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM