Reputation: 1162
I have a list of checkboxes and a div
<input class="option" value="black option" />
<input class="option" value="red option" />
<input class="option" value="green option" />
<div class="option_list"> </div>
I need the options that are checked off to show in the div.
I tried this
var option_array = new Array();
$('.option').click(function () {
var option = $(this).val();
option_array.push(option);
$('.option_list').html($.each(option_array, function (key, value) {
value + "<br>";
}));
});
It adds the selected option to the option_list
div, but does not print the html line break tag. In fact, I can take out the code between the { } and it does the same thing. I'm missing something here.
Upvotes: 0
Views: 925
Reputation: 207501
The way you are using each is not going to work, look into map().
var html = $.map(option_array,
function( value, index ) {
return value;
}).join("<br/>");
$('.option_list').html(html);
but you are not doing any logic, so I am not sure why you are not just doing a join.
$('.option_list').html(option_array.join("<br/>"));
Upvotes: 1
Reputation: 19066
Is this what you are looking for?
$(".option").on("change", function() {
$ol = $(".option_list");
$ol.empty();
$(".option:checked").each( function() {
$ol.append(this.value + "<br />");
});
});
I also changed your inputs to checkboxes, they were text?
Upvotes: 0
Reputation: 32921
I like supplying a function to .html().
$('.option_list').html(function(){
var selected = [];
$(':checked').each(function(){
selected.push($(this).val());
});
return selected.join(', ');
});
Upvotes: 0
Reputation: 6871
I would make use of HTML:
var option_array = new Array();
$('.option').click(function(){
var option = $(this).val();
option_array.push("<li>" + option + <"li">); //Wrap each option in li
var optionHTML = "<ul> + option_array.split("") + "</ul">//Wrap the whole thing in ul
$('.option_list').html(optionHTML);
});
This way you can control each list item with css, remove it with javascript or whatever
Upvotes: 0