Tje123
Tje123

Reputation: 751

How to display all checkboxes values in a div using ajax

I have multiple checkboxes displayed from MySQL table. I'm trying to pass all checked values to <div> using ajax. Currently, my code only passes one checked value to <div>. I want to display all checked values in a <div>.

What I have thus far:

 <?php
$sql="SELECT  * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result)){ ?>

<input type="checkbox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>

<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>

ajax

<script>
function showPrice(name) {
 $.ajax({
        url: 'ajax_price.php',
        type: 'GET',
        data: {option : name},
        success: function(data) {
           document.getElementById('c').innerHTML =data;
        }
    });
}
</script>

ajax_price.php

<?php
include ("../supplier/DB/db.php");
$id = $_REQUEST['option'];

 <?php
$sql="SELECT  * FROM options WHERE op_id='".$id."'";

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){

 ?> 
<div class="oder">
         <div class="odercol2"><?php echo $row['opt']; ?></div>
         <div class="odercol3"><?php echo $row['price']; ?></div>

    </div>
<?php
}
?>

This is the display with only one checked value in the <div>. I want to display all the checked values in my <div>.

checkboxes

checkboxes

Results display in this div (div id is "c")

Results display in this div

Upvotes: 0

Views: 1033

Answers (2)

BabyDuck
BabyDuck

Reputation: 1249

Just change your AJAX function to concat the innerHTML of DIV, like this:

<script>
function showPrice(name) {
 $.ajax({
        url: 'ajax_price.php',
        type: 'GET',
        data: {option : name},
        success: function(data) {
           document.getElementById('c').innerHTML += data;
        }
    });
}
</script>

Notice this line document.getElementById('c').innerHTML += data; Hope it works. Thanks

Upvotes: 1

Sundar
Sundar

Reputation: 4650

Add a class value in the checkbox

<?php
$sql="SELECT  * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result)){ ?>

<input type="checkbox" class="sundarCheckBox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>

<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>

Loop using the class name input elements

<script>
$(document).ready(function(){

    function showPrice(value){

        $.each($('.sundarCheckBox'), function(index, element){

            if($(element).is(':checked')){

                alert($(element).prop('value'));
            }           
        });     
    }   
});
</script>

Upvotes: 0

Related Questions