从数组添加和删除复选框值 [英] Adding and Removing Checkbox Values from Array

查看:72
本文介绍了从数组添加和删除复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击复选框时,我想从数组中添加和删除元素。然后将其打印到HTML文档。我通过在每次函数运行时清空数组来完成此操作,但是我宁愿删除该项而不是清空数组并添加选中的项。

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);
  }
}

HTML在这里:

<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>


推荐答案

您的代码中有很多更正,这是更新了小提琴

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


  1. 没有html输出:

  1. There was no html to output:

<p id="displaylet"></p><!-- added -->


  • 对象声明无效:

  • Declaration of object was not valid:

    var information = { /*changed*/
        letters: [] /*changed*/
    };
    


  • 函数字母也已通过几个更改:

    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);
      }
    


  • 这篇关于从数组添加和删除复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆