Mr world wide
Mr world wide

Reputation: 4814

Show Selected Multiple checkbox values as Text using jquery (Dynamic values)

Show Selected Multiple checkbox values as text. This not duplicate i have searched for it. enter image description here

Dynamic Form values:

<div class="form-group">Eligible Branch
    <select id="eligiblebranch" multiple="multiple" class="form-control" >
        <?php  $branch = $conn->query("SELECT * FROM r_branch  ORDER BY id_branch ASC");
            while ($branchresult = $branch->fetch_assoc()) { ?>
            <option value="<?php echo $branchresult['id_branch']; ?>"> <?php echo $branchresult['branch_name']; ?> </option>
        <?php } ?>
    </select>
</div> 

Script:

var checked_checkboxes = $("[id*=eligiblebranch] input:checked");
var message = "";
checked_checkboxes.each(function () {
    var value = $(this).val();
    message += + value;
    message += "\n";
});
$("#eligiblebranch1").html(message);

Output should be Text and has to visible here:

<span id="eligiblebranch1"> </span>

Upvotes: 0

Views: 1753

Answers (2)

gil.neo
gil.neo

Reputation: 173

I think you already have the answer but it needs a little modification.

var checked_checkboxes = $("[id*=eligiblebranch] input:checked");
var message = "";
checked_checkboxes.each(function () {
    var value = $(this).val();
    message += value;
    message += "<br>";
});
$("#eligiblebranch1").html(message);

Upvotes: 1

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

To get an array of values from multiple checked checkboxes, use jQuery map/get functions:

var checkedValues = $('input[type=checkbox]:checked').map(function(_, el) {
    return $(el).val();
}).get();

This will return array with checked values, like this one: ['1', '2']

You can make it as string by using join

var checkedValues = $('input[type=checkbox]:checked').map(function(_, el) {
    return $(el).val();
}).get().join(",");

Or you can use serialize() as well.

console.log($('input[type=checkbox]:checked').serialize());

Upvotes: 1

Related Questions