0

I have four checkboxes (addition, subtraction, multiplication, and division) created like this:

<input class="operation" type="checkbox" id="chkAdd" value="addition"><label>Addition</label>

I am trying to create a function that will create an array with the values of all the checkboxes that are checked when a button is pushed. The end result is to pass the array into another function that will create math problems using the selected math operators. I have looked at several similar posts, but still can't figure out why this isn't working. Here is what I have so far:

function buttonPushed() {
  var checkedBoxes = [];
  $(document).ready(function() {
    $(".theButton").click(function(event) {
      event.preventDefault();
      checkedBoxes = $(".operation input:checkbox:checked").map(function() {
        checkedBoxes.push($(this).attr('val'));
      });
    });
  });
  alert(checkedBoxes);
}

The alert is just to see if the function is working properly. Currently, when all four checkboxes are checked, and I click the button, the alert window appears, but it's empty. I have tried calling the function in <script> tags, and using the button's onclick="function()". I'm just spinning my wheels on this now. I would greatly appreciate any help.

2
  • 1
    Without jQuery: Array.from(document.querySelectorAll("input[type='checkbox']:checked"), ({value}) => value). Commented Apr 19, 2018 at 4:52
  • Thank you Xufox! I tested your solution and it worked. Commented Apr 19, 2018 at 14:04

6 Answers 6

5

jQuery map() does not return native array. You have to use get() with map(). Try the following way:

function buttonPushed() { 
  var checkedBoxes = $("input.operation:checked").map(function(){
    return $(this).val();
  }).get(); // you have use get() here
  alert(checkedBoxes);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="operation" type="checkbox" id="chkAdd" value="addition"><label>Addition</label>
<input class="operation" type="checkbox" id="chkAdd" value="subtraction"><label>Subtraction</label>
<input class="operation" type="checkbox" id="chkAdd" value="multiplication"><label>Multiplication</label>
<input class="operation" type="checkbox" id="chkAdd" value="division"><label>Division</label>
<br/><br/>
<input type="button" class="theButton" onclick="buttonPushed()" value="Get Value"/>

Sign up to request clarification or add additional context in comments.

1 Comment

Mamun, thanks for your help! I selected this as the answer because it was the closest to what I already had. Looks like I was just missing the .get(); part. My method may not be the most efficient, but I appreciate you using what I already had to try and help me solve my problem. Thanks everyone for your help!
3

If I Properly understand then this is the Solution:

<form method="POST" action="" >

    <label for="chkAdd">Addition</label>
    <input class="operation" name="math_operation[]" type="checkbox" id="chkAdd" value="addition"><br />


    <label for="chkSub">Substration</label>
    <input class="operation" name="math_operation[]"  type="checkbox" id="chkSub" value="subtration"><br />


    <label for="chkMul">Multiplication</label>
    <input class="operation" name="math_operation[]"  type="checkbox" id="chkMul" value="multiplication"><br />


    <label for="chkDiv">Division</label>
    <input class="operation" name="math_operation[]"  type="checkbox" id="chkDiv" value="division"><br />
    <input type="button" id="btn" value="Push">

and jQuery Code be like this

<script type="text/javascript">
     $('#btn').on('click',function(){
        var checkedOperations = []
        $(':checked').each( function(){
            checkedOperations.push($(this).val());
         });
    console.log(checkedOperations);
   });
</script>

Image of my output :

Output of Code

1 Comment

Er. Amit Joshi, thank you for your solution. I tested it, and it worked perfectly.
1

You need to return the mapped value from the function you pass into .map, and then use the result while still in the click handler. (you can't do it synchronously on page load - have to display the found values after the user's had a chance to click on them)

You should also put the whole code block in $(document).ready rather than putting $(document).ready( inside another function (and preferably use the more modern version, $(fn))

$(function() {
  $(".theButton").click(function(event) {
    event.preventDefault();
    const checkedBoxes = $(".operation input:checkbox:checked").map(function() {
      return $(this).attr('val');
    });
    alert(checkedBoxes);
  });
});

No need for jQuery for any of this, though

1 Comment

Thank you for your solution, Certain. I tried it, and it works.
1

There is no need of document.ready inside the function. There is no need to call a function to attach the click event.This $(".operation input:checkbox:checked") selector can be simplified

function buttonPushed() {
  var m = $.map($("input.operation:checked"), function(i, v) {
    return $(i).val()
  })
  console.log(m);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="operation" type="checkbox" id="chkAdd" value="addition"><label>Addition</label>
<input class="operation" type="checkbox" id="chkSub" value="subtraction"><label>Subtraction</label>
<input class="operation" type="checkbox" id="chkMul" value="multiply"><label>Multiply</label>
<input class="operation" type="checkbox" id="chkDiv" value="division"><label>Division</label>
<button onclick="buttonPushed()">Click</button>

1 Comment

I tried this solution, and it worked. Thank you brk!
1

There is no attribute on a checkbox call 'val' (i.e. $(this).attr('val') not going to work). Its 'value' for a start and there is a much easier way to get it $(this).val() or even this.value. The way your binding your events and alerting the array is also going to have timing issues, I mean when do you call the function buttonPushed, cause the click event is only going to be bound to the button when you call that function, so if you call it from the click of the button its kinda cart before horse, in essence all you are doing is alerting an empty array.

Firstly bind the event handler to the button before its clicked. Secondly, your jQuery selector is not correct ".operation input:checkbox:checked is trying to select any child elements that are an input of checkbox that are checked of a .operation element. The space should not be there, but of course you can't butt class and tag together, so put the tag first i.e. input.operation:checkbox:checked. and arguably the selectors being a bit over zealous, I mean .operation:checked is enough.

Hope that helps in understand. For the other issues around event binding, when to call document ready and the map function, the other answers here show enough I think to put you on the right track. There are multiple ways to skin a cat. Good luck

1 Comment

That explanation really helps! Thank you for your help, OJay.
1

its sample Example for You may be its help you to solve your issue

var matches = [];
$("#sub").click(function(){

  $(".theClass:checked").each(function() {
    matches.push(this.value);
  });

  alert(matches)  // here we are getting the all checked value

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name='cbox' value="red" class="theClass"/>red
<input type="checkbox" name='cbox' value="green" class="theClass"/>green
<input type="checkbox" name='cbox' value="yer" class="theClass"/>yer
<input type="checkbox" name='cbox' value="asdasd" class="theClass"/>asdasd
<input type="checkbox" name='cbox' value="radgdfged" class="theClass"/>radgdfged

<input type="submit" name="submit" id='sub'>

1 Comment

Lavkush, thank you for your help. I tested your solution, and it works.

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.