jeudi 16 mai 2019

Problem with counting selected checkboxes and textarea

I have a code that counts the selected checkboxes and shows them in a div.

I tried different things without succes, what I want to achieve is the following:

  • When the textarea is filled (text length > 1) --> add 1 to the result.
  • Add 1 to the result when a user types something (it should be realtime), and remove 1 when the user deletes everything in the textarea.

Count selected checkboxes (CodePen)

$('input[type="checkbox"]').change(function() {
  var selected = 0;
  var number_of_checkboxes = $('input[type="checkbox"]:checked').length;
  selected += number_of_checkboxes;
  $('#result').html(selected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="answers">
  <label for="text1">
        <input type="checkbox" name="text1" id="text1" value="1">
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </span>
    </label>
  <br>

  <label for="text2">
        <input type="checkbox" name="text2" id="text2" value="1">
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </span>
    </label>
  <br>

  <label for="text3">
        <input type="checkbox" name="text3" id="text3" value="1">
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </span>
    </label>
  <br>
  <br>

  <textarea id="selected" minlength="20" name="selected" placeholder="Lorem ipsum dolor sit amet" style="width: 500px; height: 100px;"></textarea>
  <div id="result">0</div>

</div>



Aucun commentaire:

Enregistrer un commentaire