jeudi 25 juin 2020

How to get input checked items in Javascript

1'm trying to get user Input checkbox selection using Javascript, but I'm having some issues doing it. Here is the code I'm using to achieve that:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label><input type="checkbox" onclick="toggle(this)"> Get All</label><br>
<label><input type="checkbox" name="value" value="1"> One</label><br>
<label><input type="checkbox" name="value" value="2"> Two</label><br>
<label><input type="checkbox" name="value" value="3"> Three</label><br>
<label><input type="checkbox" name="value" value="4"> Four</label><br>

<br>

<button onclick="getSelected()">Select Options</button>

<script>
  function getSelected() {

    var list = Array();

    $("input[type=checkbox]:checked").each(function() {
      list.push($(this).val());
    });
    console.log(list);

    if (Array.isArray(list) && list.length) {

      var myString = '';

      for (var i = 0; i < list.length; i++) {
        if (list.length > 1) {
          myString += '[';
          myString += list[i] + ']';
          if (i !== list.length - 1) {
            myString += ' NEST ';
          }
          console.log(myString);

        } else {
          myString = '[' + list[i] + ']';
          console.log(myString);

        }
      }

    }
    return myString;
  }

  function toggle(opc) {
    checkboxes = document.getElementsByName('value');
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = opc.checked;
    }
  }
</script>

Browser's console shows the following output:

[on] NEST [1] NEST [2] NEST [3] NEST [4]

Looking at the Input shown above, I don't have one option called "on", but the array always gives me "on" on the list.

(5) ["on", "1", "2", "3", "4"]
0: "on"
1: "1"
2: "2"
3: "3"
4: "4"
length: 5

I was expecting to get just [1] NEST [2] NEST [3] NEST [4]. I was unable to identify where that "on" option originates.

Any help or clue will be appreciated.

PS: I forgot to mention that this only happens when I mark Get All on the input option. If I mark one by one the code works fine.

Marcio




Aucun commentaire:

Enregistrer un commentaire