Click here to Skip to main content
15,797,721 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a PHP page with some checkboxes.

I need to do that: When I click on a button, an alert comes out to show me all the IDs of the selected boxes. How can I do this?

Visual example:

| BUTTON| - View the selected tests in an alert.


⬜ - - - Test 1 - - SD7168

⬜ - - - Test 2 - - BH1560

⬜ - - - Test 3 - - CP4327

So I want if, for example, I selected test 1, an alert comes to me informing me the ID (SD7168) of the test I selected.

What I have tried:

// Button 
   <a href="" class="btn btn-info" onclick="return confirm('View selected tests')">
     <br><small>TEST ID</small></a>

// Checkbox select all
    <th><input type="checkbox" name="select-all" id="select-all"/>
         <label for="select-all" class='smallLabel'></label>

// Checkbox select single

       <input type="checkbox" name="<?='checkbox-'.$num?>" id="<?='checkbox-'.$num?>"/>
          <label for="<?='checkbox-'.$num?>" class='smallLabel'></label>

// ID parameter
       <?=$test->sampleID?> Select: <input id="<?='checkbox-'.$num?>" type="checkbox"/> <br>

// JS Checkboxes

<script src=""></script>

// Listen for click on toggle checkbox
    $('#select-all').click(function(event) {   
        if(this.checked) {
            // Iterate each checkbox
            $(':checkbox').each(function() {
                this.checked = true;                        
        } else {
            $(':checkbox').each(function() {
                this.checked = false;                       

// JS che I created to manage the alert

$('<?='checkbox-'.$num?>').click(function() {
    alert("Checkbox state (method 1) = " + $('<?='checkbox-'.$num?>').prop('checked'));
    alert("Checkbox state (method 2) = " + $('<?='checkbox-'.$num?>').is(':checked'));
<script src=""></script>
Updated 6-Dec-21 6:23am

1 solution

Given that your checkboxes all have an id attribute beginning with "checkbox-" you can use the CSS "starts with" selector to pick the checkboxes up. In addition you can use the ":checked" selector. For jQuery the script would look like:

From there you can map the selected elements based on whatever property you like, and concatenate them into a string. Here's an example I threw together[^], you can replace the prop('id') bit with whatever you need to be displaying.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900