0

get all selected checkbox value and display them wanted to separate each element in the array into new line

$('#generate').on('click', function() {
      var array = [];
      $("input:checked").each(function() {
        array.push($(this).val());
      });
    
      $("#selectedSubject").text(array+'<br>'); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

4
  • 2
    Please add relevant html Commented Aug 25, 2021 at 15:13
  • array.push($(this).val() + '<br>'); $("#selectedSubject").text(array.join()); Commented Aug 25, 2021 at 15:16
  • 1
    Or even simpler ("#selectedSubject").text(array.join('<br>')); Commented Aug 25, 2021 at 15:23
  • Consider using map Commented Aug 25, 2021 at 15:31

2 Answers 2

1

ok so i fixed it myself on last line i kept using .text instead of .html thats what made me failed oof

$('#generate').on('click', function() {
  var array = [];
  $("input:checked").each(function() {
    array.push($(this).val());
  });
  let text = "";
  for (let i = 0; i < array.length; i++) {
  text += array[i] + "<br>";
  }
  $("#selectedSubject").html(text); 
Sign up to request clarification or add additional context in comments.

Comments

0

use each agian to iterate over the new array

ie:

$.each(array, function( index, value ) {
 $("#selectedSubject").append( value ); 
});

1 Comment

@GrafiCode Baby steps - if you're using each to read the values, then makes sense to use each to output them again. No each is needed for the original question (including the one in the question). Why generate an array at all? But there it is in the question.

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.