I'm working with a table in Bootstrap and one of the columns is for a checkbox. The table is filled with the values from a mysql db. In the db the column for the checkbox has a value of 1, or 0. I want the checkbox to be checked if the value is 1. I have this code, but it only works for the first checkbox. How can i use it for all checkboxes? This is my code.
<tbody>
<?php while($row = $sql->fetch()) { ?>
<tr>
<td><?php echo $row['Opleiding_ID']; ?></td>
<td><?php echo $row['Opleiding']; ?></td>
<?php $checked = $row['Hidden']; ?>
<script type="text/JavaScript">
$(document).ready(function(){
var arr<?php echo $row["Opleiding_ID"]; ?> = <?php echo json_encode($checked); ?>;
if (arr<?php echo $row["Opleiding_ID"]; ?> == "1") {
$("#mycheckbox<?php echo $row["Opleiding_ID"]; ?>").prop('checked', true);
} else {
$("#mycheckbox<?php echo $row["Opleiding_ID"]; ?>").prop('checked', false);
}
});
</script>
<td><input type="checkbox" id="mycheckbox<?php echo $row["Opleiding_ID"]; ?>" name="checks" value="" class="check"></td>
</tr>
<?php } ?>
</tbody>
$(document).ready(function() {
var arr = <?php echo json_encode($checked); ?>;
$.each(arr, function(index) {
if (arr[index] == "1") {
$("#mycheckbox").prop('checked', true);
}
});
});
Untested & probably buggy. But this is the right approach you should take. Run the elements in a loop.
if you have an auto increment id you can echo it inside the javascript code like this
<script type="text/JavaScript">
$(document).ready(function(){
var arr<?php echo $row["id"]; ?> = <?php echo json_encode($checked); ?>;
$.each(arr<?php echo $row["id"]; ?>, function(index) {
if (arr<?php echo $row["id"]; ?>[index] == "1") {
$(".check<?php echo $row["id"]; ?>").prop('checked', true);
}
});
});
</script>
<td><input type="checkbox" id="mycheckbox" name="checks" value="" class="check<?php echo $row["id"]; ?>"></td>
</tr>
<?php } ?>
</tbody>
if you re going to follow that code you should make a variable like this $id = $row["id"]; to type less
if you generate your table dynamically you can set your checkbox value there something like this .
JS :
$(document).ready(function(){
// your arr from php
var arr = [{'value' : 0 , 'name' :'Itme1' , 'description':'description1'},
{'value' : 1 , 'name' :'Itme2' , 'description':'description2'},
{'value' : 0 , 'name' :'Itme3' , 'description':'description3'},
{'value' : 1 , 'name' :'Itme4' , 'description':'description4'}];
var tableContent = '';
$.map(arr, function (item) {
checked= (item.value) ? "checked" : "" ;
tableContent+='<tr><td><input type="checkbox"'+checked+ '></td><td>' + item.name + '</td><td>' + item.description + '</td><td><input type="button" value="Edit" ></td></tr>';
});
$("#myTbody").html(tableContent);
});
Example : http://jsfiddle.net/tg5op333/39/
Related
I have a datatable filled in by SALARIES with checkbox and button update_all and dropdownlist contains CHANTIER_IDs, I want to do multiple update of CHANTIER_IDs using php / ajax .CHANTIER_IDs of SALARIES cheked in datatable will be modified by value select in dropdownlist.
I want when I click on button update all the values of chantire_ids of cheked SALARIES will be modified by the value selected in dropdownlist
affectation.php
<div class="container" id="app">
<h3>affecter salarie a chantier</h3>
<div class="form-group col-md-3 ">
<select class="form-control" id="chantier">
<?php
include "../conn/connexion.php";
$query = "SELECT id,chantier FROM chantier";
$result = mysqli_query($con,$query);
$n = mysqli_num_rows($result);
for ($i=0; $i <$n ; $i++) {
$row = mysqli_fetch_array($result);
?>
<option value="<?php echo $row[0]; ?>" ><?php echo $row[1];
} ?></option>
</select>
</div>
<button class="btn btn-success update-all" data-url="">Update All</button>
<button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
<table class="table table-bordered">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>nom & prenom</th>
<th>cin</th>
<th>matricule</th>
<th>chantier_ids</th>
</tr>
<?php
$query1 = "SELECT id,nom,prenom,cin,matricule,chantier_id
FROM salaries";
$result1 = mysqli_query($con,$query1);
$n1 = mysqli_num_rows($result1);
for ($i=0; $i <$n1 ; $i++) {
$row1 = mysqli_fetch_array($result1);
?>
<tr id="tr_<?php $row[0] ?>">
<td><input type="checkbox" class="checkbox" data-id="<?php $row[0] ?>"></td>
<td><?php echo $row1[0]; ?></td>
<td><?php echo $row1[1]; ?> <?php echo $row1[2]; ?></td>
<td><?php echo $row1[3]; ?></td>
<td><?php echo $row1[4]; ?></td>
<td><?php echo $row1[5]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
javascript
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true)) {
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
$('.update-all').on('click', function(e) {
if(confirm("Are you sure you want to delete this?")){
var id = [];
}
$(':checkbox:checked').each(function(i){
id[i] = $(this).val();
});
if(id.length === 0) //tell you if the array is empty
{
alert("Please Select atleast one checkbox");
}else{
$.ajax({
url:'delete.php',
method:'POST',
data:{id:id},
success:function(){
for(var i=0; i<id.length; i++){
$(this).parents("tr")
.children("td:last-child")
.text($('#app')
.children("option:selected")
.text());
}
}
});
}
});
});
</script>
updateall.php
<?php
include "conn/connexion";
if(isset($_POST["id"])) {
foreach($_POST["id"] as $id) {
$query = "UPDATE salaries
SET chantier_id = ". $id ."
WHERE id = '".$id."'";
mysqli_query($con, $query);
}
}
?>
Apologies if this question has been asked previously.
I am currently generating a basic table using PHP and have one cell where a user can add a comment.
When the user types a comment into the editable cell it saves it to the database table "TechComment column".
I want the editable cell to "disable editing" after the user entered the comment.
My code below:
Table Code
require_once "../linkd.php";
$sql = "select * from DispatchTech where Technician = ? and convert(date, Inserted) = convert(date,
getdate()) order by Completed ASC, DoneWhen";
$ses = $_SESSION['Username'];
$par = array($ses);
$stmt = sqlsrv_query($conn, $sql, $par);
if($stmt){
$count = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$id = $row['Id'];
$txt = $row['TechComment'];
?>
<tr>
<?PHP
if($row['Completed'] == NULL){
print "<td><button onclick=location.href='complete.php?Id=".$row['Id']."'>Complete</button></td>";
}
elseif($row['Completed'] != NULL){
print '<td><span align="center" style="font-size:15px;">✅</span></td>';
}
if($row['Area'] == NULL){
print "<td><button onclick=location.href='arrive.php?Id=".$row['Id']."'>On Site</button></td>";
}else{
print "<td>";
print date_format(new DateTime($row['Area']), "H:i:s");
print "</td>";
}
?>
<td><?php echo $row['TermID']; ?></td>
<td><?php echo $row['Location']; ?></td>
<td><?php echo $row['DMRef']; ?></td>
<td><?php echo $row['Error']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo date_format($row['Inserted'], "H:i:s") ?></td>
<td><div contentEditable='true' class="edit" id='TechComment_<?php echo $id; ?>'><?php echo $txt; ?>
</div> </td>
<td><?php echo $row['Timeframe']; ?></td>
</tr>
<?PHP
$count ++;
}
}
?>
Jquery/Ajax Code:
$(document).ready(function(){
$('.edit').click(function(){
$(this).addClass('editMode');
});
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
}
});
});
});
I found this short jquery script that will do the trick but can't get it to work.
$('.edit').editable(function (value, settings) {
return value;
});
Might it be because i'm using ajax?
I am not that familiar with ajax.
Any help will be greatly appreciated.
You can achieve it by setting contentEditable to false in your ajax response, like:
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
$('#'+id).prop('contenteditable', false );
}
});
});
I have a foreach loop on a tale row. Each row has an "edit" button to edit that row only. Using JS, I want to get a hidden open and edit the row.
Bellow is my code that I have tried but it works on one element only.
<?php
foreach($sofas as $sofa)
{
?>
<tr>
<td><?php echo $sofa["name"];?></td>
<td><?php echo $sofa["zirkar"];?></td>
<td><?php echo $sofa["parche"];?></td>
<td><?php echo $sofa["fiparche"];?></td>
<td><?php echo $sofa["mizvasat"];?></td>
<td><?php echo $sofa["asaly"];?></td>
<td>
<input onclick="myFunction()" type="button" value="ویرایش">
</td>
</tr>
<tr style="display:none;" id="<?php echo $sofa["id"];?>">
<td>
This is my DIV element.
</td>
</tr>
<?php
}
?>
<script>
function myFunction() {
<?php
foreach($sofas as $sofa)
{
?>
var x = document.getElementById("<?php echo $sofa["id"];?>");
<?php
}
?>
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I'm still learning, so please help me resolve my issue. I'm expecting the code to work on each individual table row.
Why don't you use something like this:
<?php
foreach($sofas as $sofa)
{
?>
<tr>
<td><?php echo $sofa["name"];?></td>
<td><?php echo $sofa["zirkar"];?></td>
<td><?php echo $sofa["parche"];?></td>
<td><?php echo $sofa["fiparche"];?></td>
<td><?php echo $sofa["mizvasat"];?></td>
<td><?php echo $sofa["asaly"];?></td>
<td>
<input onclick="myFunction('<?php echo $sofa["id"];?>')" type="button" value="ویرایش">
</td>
</tr>
<tr style="display:none;" id="<?php echo $sofa["id"];?>">
<td>
This is my DIV element.
</td>
</tr>
<?php
}
?>
<script>
function myFunction(id) {
var x = document.getElementById(id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Code is very simple, you only need to send the element id to the js function.
Please help me. Thanks in advance. Actually I am trying to insert selected checkbox rows into database using jquery but i don't know how to insert into DB.My jquery code is selecting the row but how to check whether the row is passing through ajax request. My table has a dynamic row from the database table with checkboxes. so when i checked the checkboxes and click the submit button then the table row should insert into the database table.
My code as below:
test.php
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
$sql = mysql_query("select * from carts where userid=13");
?>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.validate.min.js"></script>
<script src="jquery-ui.min.js"></script>
<style type="text/css">
.row_selected {background-color: #BFCBD7;}
</style>
<script>
$(document).ready(function(){
$('.chk').on('change', function() {
//alert('Hai');
var thisCheckbox = $(this);
var thisRow = thisCheckbox.closest('tr');
if ( thisCheckbox.is(':checked') ) {
thisRow.addClass('row_selected');
} else {
thisRow.removeClass('row_selected');
};
});
$('#orderSave').on('click', function(row,tr) {
//e.preventDefault();
//var toPost = $('.row_selected input').serialize();
/* Now post and insert into database */
//$.post('/invl_exams/ordercompletion', toPost, function(data) {
//alert('Success!');
//});
// Here i am creating the array to hold each selected row
var TableData = new Array();
var priVal = $(tr).find('td:eq(6)').text();
var priceVal = priVal.replace('$','');
TableData[row] = {
//column names: corresponding row data
"userid" : $('#userid').val(),
"username" : $('#hiddenUser').val(),
"date" : $(tr).find('td:eq(3)').text(),
"exam" : $(tr).find('td:eq(4)').text(),
"venue" : $(tr).find('td:eq(5)').text(),
"price" : priceVal,
"total_orders" : $(tr).find('td:eq(7)').text(),
"amount" : $(tr).find('td:eq(8)').text(),
"orders_completion" : $(tr).find('td:eq(9)').text()
}
TableData = JSON.stringify(TableData);
//console.log(TableData);
$.ajax({
type : "POST",
url : "testsubmit.php",
cache : "false",
data : {data:TableData},
success : function(result){
console.log(result);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>S.No</th>
<th>Exam Name</th>
<th>Venue</th>
<th>Date</th>
<th>Price</th>
<th>No of Orders</th>
<th>Amount</th>
<th>Checks</th>
</tr>
<?php
$i=1;
while($row = mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $i++;?></td>
<td style="display:none" id="userid">13</td>
<td style="display:none" id="hiddenUser">Gautham</td>
<td><?php echo $row['exam_name'];?></td>
<td><?php echo $row['venue'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['noOf_orders'];?></td>
<td><?php echo $row['amount'];?></td>
<td><input type="checkbox" name="chk" class="chk" value="1"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="7"> </td>
<td><button type="button" class="btn btn-success btn-xs" id="orderSave">Submit</button></td>
</tr>
</table>
</body>
</html>
testsubmit.php ( In this file i was checking the post request using print_r($_POST) )
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
//if(isset($_POST['toPost']))
//{
print_r($_POST);
//}
?>
your data inside last td is an input so you must
change from
"orders_completion" : $(tr).find('td:eq(9)').text()
to
"orders_completion" : $(tr).find('.chk')[0].checked
I found a tutorial for this with single ID. enter link description here
i have modified as per my knowledge for multiple id, i cannot able to get the id using ajax. i am not good with ajax. I have attached both code. can anyone tell how i can fix it for multiple id
i also attached a screen shot screenshot
index.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
include("connection1.php");
$result = mysql_query("SELECT * FROM mytable ORDER BY id");
?>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<div>
<table id="datatables" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["text"]; ?></td>
<td><script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch<?php echo $row["id"]; ?>').click(function(){
var myonoffswitch<?php echo $row["id"]; ?>=$('#myonoffswitch<?php echo $row["id"]; ?>').val();
if ($("#myonoffswitch<?php echo $row["id"]; ?>:checked").length == 0)
{
var a<?php echo $row["id"]; ?>=myonoffswitch<?php echo $row["id"]; ?>;
}
else
{
var a<?php echo $row["id"]; ?>="off";
}
$.ajax({
type: "POST",
url: "ajax.php",
data: "value="+a<?php echo $row["id"]; ?>,
success: function(html){
$("#display").html(html).show();
}
});
});
});
</script><div class="onoffswitch">
<input type="hidden" value="<?php echo $row["id"]; ?>" name="ids" />
<input type="checkbox" name="onoffswitch<?php echo $row["id"]; ?>" class="onoffswitch-checkbox" id="myonoffswitch<?php echo $row["id"]; ?>"
<?php
$query3=mysql_query("select * from mytable where id=$row[id]");
$query4=mysql_fetch_array($query3);
if($query4['text']=="off")
{
echo "checked";
}
?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $row["id"]; ?>">
<div class="onoffswitch-inner"></div>
<div class="onoffswitch-switch"></div>
</label>
</div>
<div id="display"></div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
Ajax.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
if(isset($_POST['value']))
{
$value=$_POST['value'];
$id=$_POST['ids'];
mysql_query("update mytable set text='$value' where id=2");
echo "<h2>You have Chosen the button status as:" .$value."</h2>";
}
?>
For your own sake ;) :
pls organize your code
add an output if something cant be loaded from your db, look therefor in the php example
why the 2. Query, you already loaded all data from 'mytable' with "select *"?
nevertheless here an example based on your code (not tested):
index.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
include("connection1.php");
$result = mysql_query("SELECT * FROM mytable ORDER BY id");
?>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<div>
<table id="datatables" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["text"]; ?></td>
<td>
<div class="onoffswitch">
<input type="hidden" value="<?php echo $row["id"]; ?>" />
<input type="checkbox" class="onoffswitch-checkbox"
<?php
if($row['text']=="off")
{
echo "checked";
}
?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $row["id"]; ?>">
<div class="onoffswitch-inner"></div>
<div class="onoffswitch-switch"></div>
</label>
</div>
<div id="display">
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('.onoffswitch').click(function(){
var hiddenValueID = $(this).children(':hidden').val();
if ($(this).children(':checked').length == 0)
{
var valueData = 'on';
}
else
{
var valueData = 'off';
}
$.ajax({
type: "POST",
url: "ajax.php",
data: {value: valueData, id: hiddenValueID} ,
done: function(html){
$("#display").html(html).show();
}
});
});
});
</script>
</div>
ajax.php
<?php
$query=mysql_connect("localhost","pma","pmapass");
mysql_select_db("testdb",$query);
if(isset($_POST['value']))
{
$value=$_POST['value'];
$id=$_POST['id'];
mysql_query("update mytable set text='$value' where id=$id");
echo "<h2>You have Chosen the button status as:" .$value."</h2>";
}
?>
You can look in your browsers-console if you get an answer from your ajax-request.