0

function submit() {
    var values = [];
    $("input[type=checkbox]:checked").each(function(){
        values.push($(this).next("value").text());
    });
    alert(values.join());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name = "top" class="checkbox" id="check1" value = "black top"/>
<input type="checkbox" name = "top" class="checkbox" id="check2" value="squish" value = "blue something" />    
<button type="button" onclick="submit()">Click Me!</button>

Above is my code for a couple of simple HTML checkboxes. I created a simple button to go along with it, and when I click it I want it to return the values of the checked checkboxes.

However, when I click the button I just get an empty alert box.

The values must not be appended to the array correctly. But I can't work out why, new to HTML/JS/JQuery.

How can I use JS or JQuery to count all the checkboxes.

messerbill
  • 5,499
  • 1
  • 27
  • 38
JoeBoggs
  • 281
  • 1
  • 5
  • 12
  • Firstly I'm not sure why you call `next()` if you want the value of the current checkbox. Also, the value can be gotten from `val()`, not `text()`. See the duplicate I marked for a more succinct way of doing this by using `map()` – Rory McCrossan Feb 27 '18 at 13:46

2 Answers2

3

You need to use $(this).val() to get the value like this

function submit() {
  var values = [];
  $("input[type=checkbox]:checked").each(function() {
    values.push($(this).val());
  });
  alert(values.join());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="top" class="checkbox" id="check1" value="black top" />
<input type="checkbox" name="top" class="checkbox" id="check2" value="squish" value="blue something" />
<button type="button" onclick="submit()">Click Me!</button>
Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31
0

With checkbox we can use this.checked to get a boolean value out of the state they are.

The jus use $(this).val() tu get the <input> value into your array.

Hope this is what you were looking for. Happy to explain or help in a better solution if needed.

function submit() {
    var values = [];
    $(".checkbox").each(function(){
      if (this.checked)
        values.push($(this).val());
    });
    alert(values.join());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name = "top" class="checkbox" id="check1" value="black top"/>
<input type="checkbox" name = "top" class="checkbox" id="check2" value="squish" value = "blue something" />    

<button type="button" onclick="submit()">Click Me!</button>
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35