0

I would like to add and remove elements from an array when a user clicks on a checkbox. This is then printed to an HTML document. I have completed this before by emptying the array each time function runs however I'd prefer to remove the item rather than empty the array and add the checked items.

https://jsfiddle.net/Buleria28/zz0x6hgc/

 /*Object that includes array*/
information {
  letters[]
}

/*Function*/
function letter() {
  var checkbox = Array.from(document.getElementsByName("test")); //creates array from checkboxes

  for (var i = 0; i < checkbox.length; i++) {
    if (checkbox.checked) {
      information.letters.push(checkbox[i].value);
    } else {
     var sbVal = checkbox[i].value;
      if (information.letters.includes(sbVal) == true) {
        var j = indexOf(sbVal);
        information.letters.splice(j, 1);
      }
    }
  }

  var showAbc = information.letters.join(", "); //converts to string
  document.getElementById("displaylet").innerHTML = showAbc; //prints to HTML document
}

/*Event Listener*/
var box = document.getElementsByName("test");
if (box[0].addEventListener) {
  for (var i = 0; i < box.length; i++) {
    box[i].addEventListener("change", letter, false);
  }
} else if (box[0].attachEvent) {
  for (var i = 0; i < box.length; i++) {
    box[i].attachEvent("onchange", letter);
  }
}

The HTML is here:

<div>
<label><input type="checkbox" name="test" value="A">A</label>
<label><input type="checkbox" name="test" value="B">B</label>
<label><input type="checkbox" name="test" value="C">C</label>
<label><input type="checkbox" name="test" value="D">D</label>
</div>



<p id="displaylet"></p>

5 Answers 5

1

Few issues with your Javascript code. Try this one: https://jsfiddle.net/zz0x6hgc/4/

/*Object that includes array*/
var information = {
  letters: []
}

/*Function*/
function letter(ev) {
  if (ev.target.checked) {
    information.letters.push(ev.target.value);
  } else {
    var index = information.letters.indexOf(ev.target.value); 
    if (index !== -1){
      information.letters.splice(index, 1);
    }
  }

  var showAbc = information.letters.join(", "); //converts to string
  document.getElementById("displaylet").innerHTML = showAbc; //prints to HTML document
}

/*Event Listener*/
var box = document.getElementsByName("test");
if (box[0].addEventListener) {
  for (var i = 0; i < box.length; i++) {
    box[i].addEventListener("change", letter, false);
  }
} else if (box[0].attachEvent) {
  for (var i = 0; i < box.length; i++) {
    box[i].attachEvent("onchange", letter);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Implementing the code the way you mentioned is not that straight forward and requires a lot of checking, especially if you want to display the letters in the correct order. Let me know if this code works for you. I added a few lines of comments.

/*Object that includes array*/
     var information = {
       letters: []
     }
     var boxes = document.getElementsByName("test");
     /* Array of Checkboxes */
     var boxesArr = Array.prototype.slice.call(boxes, 0);
     /*Function*/
     function letter(e) {
       /* Filter out the checboxes that aren't checked */
       var checkedBoxes = boxesArr.filter((checkbox) => {
         return checkbox.checked;
       });

       /* Create a new array with only the checkbox values or letters */
       information.letters = checkedBoxes.map((checkbox) => {
         return checkbox.value;
       })

       var showAbc = information.letters.join(", "); //converts to string
       document.getElementById("displaylet").innerHTML = showAbc; //prints to HTML document
     }

     /*Event Listener*/
     boxes.forEach((checkbox) => {
       if (checkbox.attachEvent) {
         checkbox.attachEvent("onchange", letter);
       } else {
         checkbox.addEventListener("change", letter, false);
       }
     })
<div>
  <label>
    <input type="checkbox" name="test" value="A">A</label>
  <label>
    <input type="checkbox" name="test" value="B">B</label>
  <label>
    <input type="checkbox" name="test" value="C">C</label>
  <label>
    <input type="checkbox" name="test" value="D">D</label>
</div>
<div id="displaylet">

</div>

Comments

0

I'd personally use a hashset for this sort of scenario, as your code will become a lot simpler.

I have made the following changes in your JavaScript:

An object that includes a letters object and a toString method to return the selected letters. The letters property will hold the selected letter as the key and a value. The toString method returns the joined representation of the letters selected.

The initialization function simply registers the 'change' event for all the checkboxes. If the checkbox os checkbox is checked, then it will be added to the letters property, or else deleted.

var information = {
    letters: {},
    toString: function() {
        return Object.keys(this.letters).join(", ");
    }
};

/*Initialize*/
(function() {
    var boxes = document.getElementsByName("test");
    for (let box of boxes) {
        box.addEventListener("change", function() {
            if (this.checked)
                information.letters[this.value] = true;
            else delete information.letters[this.value];
            document.getElementById("displaylet").innerHTML = information.toString();
        });
    }
})();

Comments

0

See if this helps:

/*Object that includes array*/
let information = {};
information['letters'] = [];

/*Function*/
function letter() {
  var checkbox = Array.from(document.getElementsByName("test")); //creates array from checkboxes

  for (var i = 0; i < checkbox.length; i++) {
    var sbVal = checkbox[i].value;

    if (checkbox[i].checked && information.letters.indexOf(sbVal) < 0) {
      information.letters.push(checkbox[i].value);
      continue;
    }

    if (checkbox[i].checked === false && information.letters.indexOf(sbVal) >= 0) {
      var j = information.letters.indexOf(sbVal);
      information.letters.splice(j, 1);
    }
  }

  var showAbc = information.letters.join(", "); //converts to string
  document.getElementById("displaylet").innerHTML = showAbc; //prints to HTML document
}

/*Event Listener*/
var box = document.getElementsByName("test");
if (box[0].addEventListener) {
  for (var i = 0; i < box.length; i++) {
    box[i].addEventListener("change", letter, false);
  }
} else if (box[0].attachEvent) {
  for (var i = 0; i < box.length; i++) {
    box[i].attachEvent("onchange", letter);
  }
}
<div>
  <label>
    <input type="checkbox" name="test" value="A">A</label>
  <label>
    <input type="checkbox" name="test" value="B">B</label>
  <label>
    <input type="checkbox" name="test" value="C">C</label>
  <label>
    <input type="checkbox" name="test" value="D">D</label>
</div>
<div id="displaylet">
</div>

Comments

0

There are lot of corrections in your code, here is the updated fiddle.

  1. There was no html to output:

    <p id="displaylet"></p><!-- added -->
    
  2. Declaration of object was not valid:

    var information = { /*changed*/
        letters: [] /*changed*/
    };
    
  3. Function letter also gone through several changes:

    information.letters.length = 0; //clear all previous selection
    var checkbox = document.getElementsByName("test"); /*changed*/
    
    for (var i = 0; i < checkbox.length; i++) {
      if (checkbox[i].checked) { /*changed, missing [i] */
        information.letters.push(checkbox[i].value);
      }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.