skip to Main Content

I have been trying to do this for a few hours but couldn’t succeed. So I decided to ask help here.

So, I have a form:

<form id="ecommerce-form">
   <input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
   <label for="seopremium" class="lead">SEO premium</label>
   <input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
   <label for="moyenpaiement" class="lead">Configuration paiements</label>
   <input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
   <label for="facturation" class="lead">Facturation simplifiée</label>
   <input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
   <label for="avisclients" class="lead">Avis clients</label>
   <input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
   <label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
   <input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
   <label for="basketoptions" class="lead">Panier avec options</label>
</form>

And I’m trying to print the label’s text of checkboxes that are checked automatically into a Paragraph:

<p class="recap-option"><strong>Options:</strong></p><p class="options-selected"></p>

So if everything is checked the Paragraph would be:

<p class="recap-option"><strong>Options:</strong></p><p class="options-selected">SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options</p>

Or in clear:

Options: SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options

I found a few solutions here for problems that seemed relatively similar but I wasn’t able to adapt the code for my own needs.

http://jsfiddle.net/5ryy9krn/2/

So the goal is simply appending what is between each into the paragraph element.

Thanks in advance for any help.

3

Answers


  1. You seem to want something like this:

    var labels = document.querySelectorAll("input:checked ~ label);
    labels.foreach(function(label) {
      console.log(label.textContent);
    });
    

    It isn’t clear to me which paragraph you want these labels added to, so I used console.log and left it for you to put the label.texContent into your paragraph(s)

    Login or Signup to reply.
  2. You need to fetch the label element and use its value to append into the selected-area.

    And on uncheck, also follow the same procedure to remove the unchecked element from the selected-area

    You can define the onChange function in the following way to achieve the expected behavior.

    $('input[type="checkbox"]').on('change', function() {
      if ($(this).is(':checked')) {
        var elements = $(this).parent('div');
        const checkedItem  = elements.find("label").text();
        $('#seleted-rows').append(`<p name="${checkedItem}">${checkedItem}</p>`);
      } else {
        var elements = $(this).parent('div');
        const uncheckedItem = elements.find("label").text();
        $('#seleted-rows').find(`p[name="${uncheckedItem}"]`).remove();
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="pb-5 devis-invisible" id="devis-ecommerce">
       <form id="ecommerce-form">
          <div class="row pb-5">
             <div class="col-4">
                <input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
                <label for="seopremium" class="lead">SEO premium</label>
             </div>
             <div class="col-4">
                <input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
                <label for="moyenpaiement" class="lead">Configuration paiements</label>
             </div>
             <div class="col-4">
                <input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
                <label for="facturation" class="lead">Facturation simplifiée</label>
             </div>
          </div>
          <div class="row">
             <div class="col-4">
                <input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
                <label for="avisclients" class="lead">Avis clients</label>
             </div>
             <div class="col-4">
                <input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
                <label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
             </div>
             <div class="col-4">
                <input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
                <label for="basketoptions" class="lead">Panier avec options</label>
             </div>
          </div>
       </form>
    </div>
    <div>
      <p>Selected Items</p>
      <div id="seleted-rows">
    
    </div>  
    </div>
    Login or Signup to reply.
  3. You have to gather all input[type=checkbox]:checked and the labels.

    Using your example this could be done with:

    var nodelistChecked = document.querySelectorAll("#ecommerce-form input[type=checkbox]:checked");
    // nodelistChecked now contains a Node-list with all checked input elements
    

    With this result you can gather the text from the labels with an Array.prototype.map function call. The result from a querySelectorAll()-call is a Nodelist and doesn’t know forEach/map/or other Array-like function-calls, so you have to call it and convert it with map to an array.

    var arrLabelText = 
      Array.prototype.map.call(nodelistChecked, function(node) {
        return (document.querySelector('label[for='+node.id+']')
          || document.createElement('label')).textContent;
      });
    // arrLabelText contains an array with all selected labels 
    // the || new element is used, to avoid errors if no label is found
    

    After this you can display the value in the element you want to display it:

    document.querySelector("p.options-selected").innerText = arrLabelText.join(', ');
    

    When you use jQuery it is a a bit shorter and it avoids some error-checking (like no label found):

    function fillSelectedOptions() {
      $("p.options-selected").text(
        Array.prototype.slice.call( // depending on the jQuery version, this might be required
          $("#ecommerce-form input[type=checkbox]:checked")
            .map(function(i,node) { /* jQuery returns the index first */
              return $('label[for="'+node.id+'"]').text()
            })
        ).join(', ')
      );
    }
    $("#ecommerce-form input[type=checkbox]").each(function(i, node) {
      $(node).on('change', fillSelectedOptions);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search