0

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(', '));
   });
});
2
  • you're way overthinking this and doing way to much work Commented Apr 4, 2016 at 13:09
  • var arr = $('input').serializeArray() And if you just need the values var arr = $('input').serializeArray().map(function(v,k) { return v.value }) Commented Apr 4, 2016 at 13:14

3 Answers 3

1

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/[email protected]" 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>

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

Comments

0

A checkbox has no value. You set var checkbox = $(this).val() and then check if $(checkbox).is(':checked') Just use $(this).is(':checked')

Comments

0

You want to bind to change events on the checkbox rather than on click events on the whole document. I.e this section does not make any sense:

$(document).on('click', function(event) {
   $('input:checkbox').on('click', function() {
     ... 
   });
});

Literally it binds a new click handler on all checkboxes whenever you click anywhere in the document.

Here's a working example:

$(document).ready(function() {
  var output = $('#serviziSection2Def');
  $('.servizioSection2:checkbox').change(function() {
    output.text($('.servizioSection2:checkbox:checked').map(function() {
      return $(this).val();
    }).get().join(', '));
  })
});
h1 { font-size: 16px; } /* just for readability on SO, ignore */
<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="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>

<div id="serviziSection2Def">
</div>

Note on the side: Never ever use element.html(...) with unsanitized user input, since this can break your website layout. Use element.text(...) whenever possible, this escapes entered HTML.

Comments

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.