jqueryhtmlcheckbox

Checkbox status jQuery


I have this HTML and I have to check which one of these checkboxes is checked and get the value of the selected checkbox to add it to an array. I've tried different code but I don't know where is the problem

<div class="row ">   
    <div class="col-md-5 col-md-offset-1 col-centered ">
        <input type="checkbox" id="piega1" class="servizioSection2" name="imgSection2"value="PiegaByWellaProfessionals">
        <label class="piega" for="piega1">
            <img src="img/piega1.png" for="piega1" alt="" class="img-responsive immaginePiega ">
        </label>
        <h1 class="immagineTitoloPiega">PIEGA BY WELLA PROFESSIONALS</h1>
    </div>
    <div class="col-md-5  col-centered piege">
        <input type="checkbox" id="piega2" name="imgSection2" class="piege servizioSection2" value="PiegaBySystemProfessionals">
        <label for="piega2" class="piega ">
            <img src="img/piega2.png" for="piega2" alt="" class="img-responsive immaginePiega">
        </label>
        <h1 class="immagineTitoloPiega">PIEGA BY SYSTEM PROFESSIONALS</h1>
    </div>
</div>

and this is the jQuery to check the checkbox status. I also don't know why if I click on a checkbox I get the value of all of them and not just the one I clicked

$(document).on('click', function(event) {
   var serviziSection2 = $('#serviziSection2Def');
   $('input:checkbox').on('click', function(){
     var servizi = [];
     $('.servizioSection2:checkbox').each(function(){
       var checkbox = $(this).val();
             console.log(checkbox)
       if($(checkbox).is(':checked') == true){
           servizi.push(checkbox.next('label').html());
           console.log(servizi)
       }
     });
     serviziSection2.html(servizi.join(', '));
   });
});

Solution

  • First of all, you're assigning a new click event to all checkbox's every time anything in the document is clicked on. Secondly, jQuery already comes with some simple built in features for this. Take a look at .serializeArray()

    What you're trying to achieve is as simple as:

    //  this is typical starter for a block of jQuery code.
    //  this is same as document.ready = function() { ...
    $(function() {
      //  this sets events on ALL elements matching selector, 
      //  including dynamically created ones (inserted by JavaScript code)
      $(document)  //  as you can see, i'm assigning a 'change' event to 'input[type=checkbox]'s
        .on('change', 'input[type=checkbox]', function(e) {
          //  first i set a variable containing an array of Name/Value Objects of all CHECKED checkboxes
          //  this will NOT grab values of any unchecked box
          var checked = $('input').serializeArray(),
              //  this next variable simply creates an array of ONLY the values from our previous array.
              values = checked.map(function(val, key) { return val.value });
          
          //  display values as a single string of text
          $('fieldset pre').text(values.join(', '));
          
          //  and if you still want that HTML part
          //  this first variable gets all labels that only follow CHECKED inputs
          var $checkedInputs = $('input:checked + label'),
              //  creating simple placeholder element variable to get all the HTML onto
              newHTML = $('<div/>');
          //  add each needed piece of HTML to our placeholder
          $checkedInputs.each(function(index) { newHTML.append($(this).html()); });
          //  display output of our new HTML
          //  newHTML.html() will output ONLY the html we put into it, and NOT the outer div created for this variable
          $('fieldset p').html(newHTML.html());
        });
    })
    img { height: 50px; }
    h1 { display: inline-block; font-size: 1.25em; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="row ">   
        <div class="col-md-5 col-md-offset-1 col-centered ">
            <input type="checkbox" id="piega1" class="servizioSection2" name="imgSection2"value="PiegaByWellaProfessionals">
            <label class="piega" for="piega1">
                <img src="http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png" for="piega1" alt="" class="img-responsive immaginePiega ">
            </label>
            <h1 class="immagineTitoloPiega">PIEGA BY WELLA PROFESSIONALS</h1>
        </div>
        <div class="col-md-5  col-centered piege">
            <input type="checkbox" id="piega2" name="imgSection2" class="piege servizioSection2" value="PiegaBySystemProfessionals">
            <label for="piega2" class="piega ">
                <img src="https://i.sstatic.net/CE5lz.png" for="piega2" alt="" class="img-responsive immaginePiega">
            </label>
            <h1 class="immagineTitoloPiega">PIEGA BY SYSTEM PROFESSIONALS</h1>
        </div>
    </div>
    <fieldset>
      <legend>Output</legend>
      <h3>values</h3>
      <pre></pre>
      <hr />
      <h3>HTML</h3>
      <p></p>
    </fieldset>