Abdul Waheed Abdul Waheed - 2 months ago 14
Ajax Question

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>

Answer

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());
Comments