simonfoust
simonfoust

Reputation: 131

Add html to a list of values pulled from checked checkboxes

Here is my HTML:

<ul>
    <li>
        <input type="checkbox" id="data_patient-name" value="Patient Name" class="checkbox">
        <label for="data_patient-name">Patient Name</label>
    </li>
    <li>
        <input type="checkbox" id="data_wait-time" value="Wait Time" class="checkbox">
        <label for="data_wait-time">Wait Time</label>
    </li>
    <li>
        <input type="checkbox" id="data_patient-satisfaction" value="Patient Satisfaction" class="checkbox">
        <label for="data_patient-satisfaction">Patient Satisfaction</label>
    </li>
</ul>

Here is my JavaScript:

$(".checkbox").on("change", function(){
    var reportFields = [];
    $('.checkbox:checked').each(function(){        
        var fieldValues = $(this).next().text();
        reportFields.push(fieldValues);
    });
    $("ul.report-fields").html(reportFields.join(", "));
});

So this gives me a comma delimited list of values from checked checkboxes, awesome! However, I need to include some more information with that list of values. Namely, each value needs to be a list item that has a class name corresponding to the id of the checkbox. So in the end, I need to get a list that looks like this:

<ul class="report-fields">
    <li class="data_patient-name">Patient Name<sup><a href="#" class="remove" title="Remove">x</a></sup></li>
    <li class="data_wait-time">Wait Time<sup><a href="#" class="remove" title="Remove">x</a></sup></li>
    <li class="data_patient-satisfaction">Patient Satisfaction<sup><a href="#" class="remove" title="Remove">x</a></sup></li>
</ul>

So I've been playing around with the line in my JS:

$(".buildReportBox .report-fields ul").html(reportFields.join(", "));

but I'm having a lot of trouble.

Upvotes: 0

Views: 137

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

You can use wrap function to do so:

$("ul.report-fields").html(reportFields.join(" ")).each(function(){
    $(this).wrap('<a class="yourclass" href="#path" />');
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Try

$(".checkbox").on("change", function () {
    var reportFields = $('.checkbox:checked').map(function () {
        var $this = $(this);
        return '<li class="' + this.id + '">' + $this.next().text() + '<sup><a href="#" class="remove" title="Remove">x</a></sup></li>'
    }).get();
    $("ul.report-fields").html(reportFields.join(''));
});

Demo: Fiddle

Upvotes: 1

Related Questions