devomac devomac - 7 months ago 9
Javascript Question

Assigning Elements to array then printing jquery

I am having an issue where I need to put value from checkboxes into an array, then use toString() on the array and write the array contents to a div. Any help would be really appreciated.

<form id="form" action="" onsubmit="return false">
<div id="inputs" class="alignAndWhiteText">
<div style="margin-left:80px">
<label>List music in the order you prefer</label>
<hr style="margin-right:80px"/>
<div id="selections">
<input type="checkbox" id="popMusic">Pop Music<br>
<input type="checkbox" id="metalMusic">Metal Music<br>
<input type="checkbox" id="countryMusic">Country Music<br>
<input type="checkbox" id="rapMusic">rap Music<br>
<input type="checkbox" id="electronicMusic">Electronic Music<br>
</div>
<div id="userFeedback" style="color:white;text-align:center"><p></p></div>
</div>
</div>
</form>

$(document).ready(function(){
var music = ["","","","",""];
$('#popMusic').click(function(){
music.push($('#popMusic').val());
});
$('#metalMusic').click(function(){
music.push($('#metalMusic').val());
});
$('#countryMusic').click(function(){
music.push($('#countryMusic').val());
});
$('#rapMusic').click(function(){
music.push($('#rapMusic').val());
});
$('#electronicMusic').click(function(){
music.push($('#electronicMusic').val());
});
music.toString();

for(i = 0;i < music.length; i++){
$('#userFeedback').html(music);
}


});

Answer

Is this you wanted? I have refactored code and leverage each of jQuery.

$(document).ready(function(){
var music = [];
  $( ".musicSelection" ).each(function( index ) {
    $(this).change(function() {
      if($(this).is(':checked')) {
          $('#userFeedback').append("<p>" + $(this).val() + "</p>");
         }
    });
         
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="" onsubmit="return false">
        <div id="inputs" class="alignAndWhiteText">
            <div style="margin-left:80px">
                <label>List music in the order you prefer</label>
                <hr style="margin-right:80px"/>
                <div id="selections">
                <input class="musicSelection" type="checkbox" id="popMusic" value="Pop Music">Pop Music<br>
                <input class="musicSelection" type="checkbox" id="metalMusic" value="Metal Music">Metal Music<br>
                <input class="musicSelection" type="checkbox" id="countryMusic" value="Country Music">Country Music<br>
                <input class="musicSelection" type="checkbox" id="rapMusic" value="rap Music">rap Music<br>
                <input class="musicSelection" type="checkbox" id="electronicMusic" value="Electronic  Music">Electronic  Music<br>
                </div>
                <div id="userFeedback" style="color:tomato;text-align:center"><p></p></div>
            </div>
        </div>
    </form>