Click here to Skip to main content
15,848,264 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.

⬜ ALL | PRODUCT | SAMPLE ID

⬜ - - - 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:

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

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

// Checkbox select single

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

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


JavaScript
// JS Checkboxes

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Posted
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:
JavaScript
$('input[id^="checkbox-"]:checked');

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