2

I have form containing checkboxes,i want to populate their data from database through ajax, I want to make the available products checked as the value in the database ,also if the data in the database is rather than "Cacao, Coconuts, Bananas" i have to put it in the textbox of others checkbox "ex: Apple" i did that for the textbox but i couldn't for checkbox, how can this be done?

Html code

<div class="row">
<div class="col-sm-4">
    <label class="Modallabel">Available Products:</label>
</div>
<div class="col-sm-8">
    <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Cacao">Cacao</label>
    <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Coconuts">Coconuts</label>
    <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Bananas">Bananas</label><br>
    <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" id="optcheck" value="Others">Others</label>
     <input type="text" id="Other_pro" name="otherproduct" disabled><br>
    <label id="Note">(Separate Products with commas)</label>
</div>

Ajax

$.ajax({
    type:"POST",
    url:"EditFarmerData.php",
    dataType: 'json',
    data:{'EditFarmerID': EditFarmerID},
    success: function (data) 
        {
            $("#EditFarmerFName").val(data.FarmerFirstName) ;

        }
})

PHP Code

$EditFarmerID = $_POST['EditFarmerID'];

    $sql="SELECT * FROM Farmers where Farmer_ID='".$EditFarmerID."'";

    foreach ($conn->query($sql) as $row)
        {
            $FarmerFirstName=$row['first_name_'];
            $FarmerAvailableProducts = $row['Available_Products'];
        }
    $json = array(
        "FarmerFirstName" => $FarmerFirstName,
        "FarmerAvailableProducts " => $FarmerAvailableProducts 
        $categories = '';
            $cats = explode(",", $FarmerAvailableProducts);
            foreach($cats as $cat) {
                $cat = trim($cat);
                $categories .= "<category>" . $cat . "</category>\n";
            }
    );
    echo json_encode($json);
NewDeveloper
  • 105
  • 3
  • 12

2 Answers2

2

You can use Attribute Equals Selector [name="value"] to get the checkboxes with particular value.

 $("input[type=checkbox][value=Bananas]").prop("checked",true);

In your case, you have to check response and you can go with loop and change value=bananas with your variable

Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
0

Use the below code:

success: function (data) 
{
    ...
    ....
    $('input[value="'+data.FarmerFirstName+'"]').prop('checked', 'checked');
    ....
    ....
}

Hope this will help