简体   繁体   中英

replace div with list of array items in jquery .html

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.

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/>"));

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

I like supplying a function to .html().

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM