简体   繁体   中英

How to create an array with values of all checked checkboxes in jQuery

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.

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 :

代码输出

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

There is no attribute on a checkbox call 'val' (ie $(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 ie 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

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> 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM