0

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.

4 Answers 4

1

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/>"));
Sign up to request clarification or add additional context in comments.

2 Comments

map returns an array, you can't call .get() on it. The function also doesn't get passed "key" and "value". It is "element" and "index". As a result "value" here is the array index.
I forgot to swap it out from copying the original post, changed it around.
0

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

Comments

0

I like supplying a function to .html().

$('.option_list').html(function(){
  var selected = [];
  $(':checked').each(function(){
    selected.push($(this).val());
  });
  return selected.join(', ');
});

Comments

0

Is this what you are looking for?

http://jsfiddle.net/DPXD2/1/

$(".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?

Comments

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.