Get checkboxes checked every time you check or uncheck one [closed]

1

I can not get checkboxes marked (one of the checkboxes is marked since its creation), what is my error?

                            
function activar(){
   var yourArray=[];
   $("input:checkbox[name=vehicle]:checked").each(function(){
        yourArray.push($(this).val());
   });
   console.log(yourArray);
}                  

activar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>

I try to tell me, every time I check or uncheck one of the checkboxes, which are the checkboxes that are marked.

    
asked by hubman 25.03.2017 в 19:53
source

2 answers

2

If I have not misunderstood what you want to do, it is to tell you each time you check or uncheck one of the checkboxes that are checked.

To do this, you can add the function onclick to each of the checkbox and this way each time you click on them to mark / unmark them the response will appear at that moment.

function activar(){
  var yourArray=[];
  $("input:checkbox[name=vehicle]:checked").each(function(){
     yourArray.push($(this).val());
  });
  console.log(yourArray);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike" onclick="activar()"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked onclick="activar()"> I have a car<br>
    
answered by 25.03.2017 / 20:12
source
0

If I do not understand, do you want no checkbox to be checked? it would be enough to remove the checked from the input

 <input type="checkbox" name="vehicle" value="Car"> I have a car<br>

Also when you capture the checked with the name, you have to put the id attribute and its name has to be different in each one

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input id="id_bike" type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input id="id_car" type="checkbox" name="vehicle" value="Car" checked> I have a car<br>

Use this line, it will bring the checked checkbox

  

vehicle var = $ ('input [name = vehicle]: checked'). val ();

    
answered by 25.03.2017 в 20:06