I'm doing crud (CREATE, READ, UPDATE, DELETE) table in PHP + JS + SQL and I want to do the next:
I have a table with users (I take this data from my DB):
When I click on the "Edit" icon (green edit icon), I can type on the values of my table.
I don't know how to get the exact position of the array (to show all of those users, I'm using an array, ofc) to save it in a variable for later do a query to update the information.
Do you know what I'm trying to say, guys?
Here is my code:
<table class='table table-bordered table-hover' class='display' style='width:100%; text-align: center;' id='tableTest'>
<thead>
<tr>
<th>Editar</th>
<th>Nombre</th>
<th>Apellido 1</th>
<th>Apellido 2</th>
<th>Email</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<?php foreach ($res_table as $r){ ?>
<tr>
<td><span class="fas fa-edit editar grow" onclick="updateData(this)"></span></td>
<td><?php echo $r->usuario?></td>
<td><?php echo $r->apellido1?></td>
<td><?php echo $r->apellido2?></td>
<td><?php echo $r->email?></td>
<td><span class="fas fa-trash-alt grow" onclick="updateData(this)"></span></td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="contenedorForm">
</div>
And here is my JS.
// FunciĆ³n para actualizar los datos de la tabla.
function updateData(nodo){
var nodoTd = nodo.parentNode; //Nodo TD
var nodoTr = nodoTd.parentNode; //Nodo TR
var nodoContenedorForm = document.getElementById('contenedorForm'); //Nodo DIV
var nodosEnTr = nodoTr.getElementsByTagName('td');
var editData = nodosEnTr[0].textContent;
var usuario = nodosEnTr[1].textContent;
var apellido1 = nodosEnTr[2].textContent;
var apellido2 = nodosEnTr[3].textContent;
var email = nodosEnTr[4].textContent;
var opciones = nodosEnTr[5].textContent;
var nuevoCodigoHtml =
'<td><span class="fas fa-edit editar grow" onclick="updateData(this)"></span></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="usuario" id="usuario" value="' + usuario + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="apellido1" id="apellido1" value="' + apellido1 + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="apellido2" id="apellido2" value="' + apellido2 + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="email" id="email" value="' + email + '" size="20"></td>' +
'<td><span class="fas fa-trash-alt editar grow" onclick="updateData(this)"></span></td>';
nodoTr.innerHTML = nuevoCodigoHtml;
nodoContenedorForm.innerHTML =
'Pulse Aceptar para guardar los cambios o cancelar para cancelActionlos' +
'<form name = "formulario" action="general" method="get" onsubmit="capturarEnvio()" onreset="cancelAction()">' +
'<input class="boton" type = "submit" value="Aceptar">' +
'<input class="boton" type="reset" value="Cancelar">';
}
function getIdInputFromDatabase(){
alert("I NEED TO KNOW THE POSITION OF THE ARRAY WHERE I DID ON BLUR");
}
// Data tables.
$(function () {
$('#tableTest').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json"},
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": false,
"autoWidth": false,
"scrollX": false
});
});
</script>
How Can I do this, guys? Can you help me? I searched on the DataTables API but Im lost.
Thank you in advance!
Have a good day!
As you have a field called ID you can store that in the HTML when you first build your table (in the <?php foreach ($res_table as $r){ ?> loop), this can be either as an attribute to the tr, eg
<tr data-id='<?php echo $r->id?>'>
or in a hidden td, eg
<td style='display:none;'><?php echo $r->id?></td>
(don't use style='display:none' use a css to hide it, just an example here to show it's hidden).
Then your edit can know which row is being edited by its ID (rather than row index, which may not match the DB ID)
var id = $(nodoTr).data("id")
or
var id = nodoTr[0].textContent;
You then need to pass that id to your inline edit, in some way, this could be by adding as a parameter to the onsubmit, eg:
'... onsubmit="capturarEnvio(' + id + ')" ...'
Related
This is what I tried to do but I can't get it to work, can anyone help me.
I would like to click on the approve button and get value of input with name="documentno" of the same row as the button I clicked on.
Thank you
<form class="form-inline" action="approval.php" method="post"enctype="multipart/form-data">
<table class="table table-hover" id="detailTable">
<thead>
<tr>
<th>Document no</th>
<th>Code</th>
<th>Name</th>
<th>Approve</th>
<th>Reject</th>
</tr>
</thead>
<tbody>
<tr id="somerow">
<?php
if($select==""){
while($rowstep34id = mysqli_fetch_array($querystep34)){
//echo "<td>" . $rowstep3['itemcode'] . "</td><td>" . $rowstep3['itemdescription'] . "</td><td>" . $rowstep3['quantity'] . "</td><td>" . $rowstep3['unitprice'] . "</td><td>" . $rowstep3['total'] . "</td><td>" . $rowstep3['remarks'] . "</td></tr>";
echo "<td><input type='text' name='documentno' value='" . $rowstep34id['id'] . "' readonly /></td>
<td><input type='text' name='vendorcode' value='" . $rowstep34id['code'] . "' readonly /></td>
<td><input type='text' name='vendorname' value='" . $rowstep34id['name'] . "' readonly /></td>
<td><button type='button' class='btn btn-primary' name='approve' onclick='tgPanel(this)'>approve</button></td>
<td><button type='button' class='btn btn-primary' name='reject'>reject</button></td>
</tr>";
}
}
?>
</tbody>
</table>
</form>
<script>
function tgPanel(button) {
var tr = button.parentElement.parentElement;
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
}
</script>
If you could define some id or data-id to your rows it would be possible to do smth like that:
$(#row-id button).on("click", function{tgPanel($(this)});
function tgPanel(button)
{
var data= button.closest("input[name='documentno']").val();
}
With your current markup you can get the value of documentno input from the same row by the following.
function tgPanel(button) {
let documntnoVal = button.closest('tr').querySelector('input[name="documntno"]').value;
//remaining code ....
}
//The idea is when you click the approved button just select the parent tr (which will be the row containing approved button that is just clicked) and then select the input with name="documntno" which is your desired element.
NOTE: In your markup it seems you missed an opening "< tr >" tag in echo, so please make sure your markup is valid.
Hello devs/programmers/coders.. When I press Tab to proceed to the next row NaN value is automatically inputted, and even onclick gives me NaN, then the sum of the total column will NaN and will not change.. I have no idea on how will I remove the NaN value... please help me! Here is my code:
<html>
<link rel = "stylesheet" href = "styling.css?version=3"></link>
<body>
<div id='acctdetails' style='padding-left: 15% '>
<?php
echo "USERNAME: ". $_SESSION["dynau"];
?>
OR Date: <input type='text' placeholder='OR Date' name='ordate' value='<?php echo date('M, d, Y');?>'>
OR ID: <input type='text' placeholder='OR ID' name='orid'>
Payor : <input type='text' placeholder='Payor' name='payor' >
</div>
<center>
<form method="POST">
<?php
$result = mysqli_query($link,"SELECT * FROM account_db");
echo"<html>";
echo "<script>";
echo "function calculate(amount, id){
document.getElementById('total' + id).innerHTML = parseInt(document.getElementById('copy' + id).value) * amount;
var x=parseInt(document.getElementById('total' + id).innerHTML);
var y = document.getElementById('sumtotal').innerHTML;
var a = y.split(' ');
var z = parseInt(a[1]) + parseInt(x);
document.getElementById('sumtotal').innerHTML = 'Total: ' + z;
}";
echo "</script>";
echo"<center>";
echo "<form method='POST'>";
echo "<br></br>";
echo "<table style='border:1px solid black' id='thetable' name='pleasework'>";
echo"<th>FILES</th>";
echo"<th>AMOUNT</th>";
echo"<th>NO. OF COPIES</th>";
echo"<th>TOTAL AMOUNT</th>";
$counter = 0;
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
echo "<td >$row[1] </td>";
echo "<td align=center>$row[2] </td>";
echo "<td align=center>
<input type='number' id='copy" . $counter . "' onkeyup='calculate(" . $row[2] . ", " . $counter . ")'>
</td>";
echo "<td align=center id='total" . $counter . "'></td>";
echo"</tr>";
$counter++;
}
echo"<tr>
<td id='sumtotal'>TOTAL: 0</td>
</tr>";
echo "</table>";
echo " <br><div style='padding-left: 15px'><input type='submit' id='btn1' value='Transact' name='transaction' onclick='javascript: window.print()'></div>";
echo"</center>";
echo"</html>";
?>
</center>
</body>
</html>
Your first issue is in this line:
document.getElementById('total' + id).innerHTML = parseInt(document.getElementById('copy' + id).value) * amount;
In order to understand the issue you can try by yourself:
parseInt('')
The result of the previous operation is undefined, so:
parseInt('')+amount
will be NaN (not a number).
That means you need to test the value before to proceed with the computation:
!!ele.value.trim() --> value is not empty
I suggest you to use:
.value (for input field): The initial value of the control. This attribute is optional except when the value of the type attribute is radio or checkbox.
Note that when reloading the page, Gecko and IE will ignore the value specified in the HTML source, if the value was changed before the reload.
.textContent(for cell with text values): represents the text content of a node and its descendants
instead of:
.innerHTML : sets or gets the HTML syntax describing the element's descendants.
Moreover, in order to simplify your code you may consider to traverse the dom in order to get the values contained in the other two sibling cells.
Use the keyword this in your case. This keyword stands for the current element, so you don't need to get it from the dom.
The snippet:
function calculate(ele) {
if (!!ele.value.trim()) {
var x = +ele.value * +ele.parentElement.previousElementSibling.textContent.trim();
var y = +document.getElementById('sumtotal').textContent.trim().split(' ').pop();
ele.parentElement.nextElementSibling = x;
var z = x + y;
document.getElementById('sumtotal').textContent = 'Total: ' + z;
}
}
<div id='acctdetails' style='padding-left: 15% '>
USERNAME: ...
OR Date: <input type='text' placeholder='OR Date' name='ordate' value='01/01/2017'>
OR ID: <input type='text' placeholder='OR ID' name='orid'>
Payor : <input type='text' placeholder='Payor' name='payor'>
</div>
<form method="POST"><br/>
<table style='border:1px solid black' id='thetable' name='pleasework'>
<th>FILES</th>
<th>AMOUNT</th>
<th>NO. OF COPIES</th>
<th>TOTAL AMOUNT</th>
<tr>
<td>1</td>
<td align=center>11</td>
<td align=center>
<input type='number' id='copy1' onkeyup="calculate(this)">
</td>
<td align=center id='total1'></td>
</tr>
<tr>
<td id='sumtotal'>TOTAL: 0</td>
</tr>
</table>
<br>
<div style='padding-left: 15px'><input type='submit' id='btn1' value='Transact' name='transaction'
onclick='javascript: window.print()'></div>
</form>
I wish anybody help me here, its very big problem for me.. I want to implement javascript into check_data.php but this is can't be done maybe becuase this page doesn't appear in the browser, index.php display table from check_data.php but for some reasons i need to implement javascript into check_data.php any help?
index.php:
<input type= "text" name= "datepicker" id="datepicker" class="form-control" />
</div>
<script>
$('#datepicker').change(function () {
$.post('check_data.php', {
dtpickerdate : $(this).val()
}, function (response) {
$('table').html(response);
});
});
$("#datepicker").datepicker({dateFormat: "mm-dd-yy",})
.datepicker("setDate", new Date()).change();
</script>
Check_data.php
<table id = "table" class = "table table-bordered">
<thead class = "alert-info">
<tr>
<th>Kitchen Time</th>
<th>Order#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Driver#</th>
<th>Delivery Time</th>
<th># of People</th>
<th>Miles</th>
</tr> </thead><tbody>
<?php
$dtpickerdate = isset($_POST['dtpickerdate']) ?
$_POST['dtpickerdate'] : NULL;
$q_customer = $conn->query("SELECT * from orders inner
JOIN customer_order on
customer_order.order_no =orders.order_no
and orders.date like'$dtpickerdate' inner join
driver_order on
driver_order.order_no=orders.order_no
LEFT JOIN customer on
customer.phone=customer_order.phone
order by k_time,time desc" )
or die(mysqli_error());
$k_time = '';
while($f_customer = $q_customer->fetch_array()){
$s=mysqli_num_rows($q_customer);
?>
<tr>
<?php
if($k_time == '' || $k_time != $f_customer['k_time']){
$k_time = $f_customer['k_time'];
echo '<td align="center" > <span style=" font-weight:bold;">'
.$f_customer['k_time']. '</td>';
} else{
echo "<td td style=' border: none;'> </td>";
}
echo "<td style='background-color: #5f5d5d; ' align='center' span style='font-weight:bold;'> <a href = '#' style='color:#ececec;font-weight:bold;' data-toggle = 'modal' data-target = '#action'>".$f_customer['order_no']."</a></td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>" .$f_customer['first_name']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['last_name']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['address']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['driver_no']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['d_time']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['no_ofppl']."</td>";
}
Looks like you are trying to load the HTML into the page via ajax.
You can try jQuery.load():
page.php
$('table').load('check_data.php');
Edit: It seems like you are confused about the difference between JavaScript and PHP, and when/how to use each. However, to answer your question, you could put additional JavaScript into another file, and load that as well.
page.php
$('table').load('check_data.php', function() {
$.getScript('alert.js');
});
alert.js
alert('hi');
I have a page that present a big table in my SQL DB, and every cell is an HTML input.
The goal is to make a editable sql table that update my SQL DB based on changed in specific cell in big table form.
I tought about making a script that trigger a JS function when a cell-change occurs, that update the specific change.
Is it possible?
Any other idea?
This is a draft of my idea. The issue is the While loop that present the table
<script>
$(document).ready(function(){
$('#testnum').on('change', 'input', function(){
$.post("getter.php",{###Don't know what to put here###);
});
});
</script>
<?php
while($res=mysqli_fetch_array($result))
{
echo "<tr>
<td onchange='changeit(fin)'>
<div name='fin' style='display:none;'> ".$res['first'] ."</div>
<input type='int' value=".$res['first'].">
</td>
<td onchange='changeit(sta)'>
<div name='sta' style='display:none;'>".$res['second']."</div>
<input type='int' value=".$res['second'].">
</td>
<td>";
?>
EDIT
For example - how can I pass David's ID if I change his city?
(This table printed with WHILE statement)
ID name city
-------------------
1 David NY
--------------------
2 John LA
-------------------
3 Adam NJ
if I change David's city to "London" for example I want to send 3 things:
1) The ID - so I know which specific row. (in this case - "1")
2) The column name - so I can know which column has changed. (in this case - "city")
3) The data after change - so I know what to update. (in this case - "London")
Hi you can use something similar to this, you'll need to adapt it to your code and needs.
HTML FILE:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Check</title>
</head>
<body>
<table>
<tbody>
<tr class="row">
<td class="col id"><input class="txtdata" name="id" value="1"></td>
<td class="col name"><input class="txtdata" name="name" value="Jhon"></td>
<td class="col city"><input class="txtdata" name="city" value="NY"></td>
</tr>
<tr class="row">
<td class="col id"><input class="txtdata" name="id" value="2"></td>
<td class="col name"><input class="txtdata" name="name" value="Jane"></td>
<td class="col city"><input class="txtdata" name="city" value="LA"></td>
</tr>
</tbody>
</table>
</body>
<script type='text/javascript' src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
</html>
<script>
$(document).ready(function($) {
$('.txtdata').on('change', function(){
var parent = $(this).parent('.col').parent('.row');
var id = $(parent).find('.id').find('input').val();
var name = $(parent).find('.name').find('input').val();
var city = $(parent).find('.city').find('input').val();
var attribChanged = $(this).attr('name');
data = {id: id, name: name, city: city, attribChanged: attribChanged};
$.post('getter.php', data, function(data){
$(parent).html(data);
});
});
});
</script>
PHP FILE:
<?php
$name = $_REQUEST['name'] . '(mod)';
$id = $_REQUEST['id'] . '(mod)';
$city = $_REQUEST['city'] . '(mod)';
echo '<td class="id"><input class="txtdata" name="id" value="'.$id.'"></td>
<td class="name"><input class="txtdata" name="name" value="'.$name.'"></td>
<td class="city"><input class="txtdata" name="city" value="'.$city.'"></td>';
?>
PHP file:
<?php
echo '<table>';
while($res=mysqli_fetch_array($result)){
echo '<tr>';
echo '<td>$res['id']</td>';
echo '<td onchange="changeit($res['id'], \'name\', this)"><input type="text" value="$res['name']"/></td>';
echo '<td onchange="changeit($res['id'], \'city\', this)"><input type="text" value="$res['city']"/></td>';
echo '</tr>';
}
echo '</table>';
Jquery:
function changeit(id, field, element){
var newVal = element.find('input').val();
$.post("getter.php",{
"id": id,
"field": field,
"newVal": newVal
}, function(result){
if(result == 'success'){
alert('id: '+ id);
alert('column: '+ field);
alert('what change: '+ newVal);
}
});
}
PHP file getter.php:
$id = $_POST['id'];
$field = $_POST['field'];
$newVal = $_POST['newVal'];
$sql = mysql_query("UPDATE table_name SET $field = $newVal WHERE id = $id");
if($sql) echo 'success'; else echo '0';
Hope helpful for you.
I have a html table. Inside that my markup is like this:
<table id="invoices-product-detail">
<tbody id="tableToModify">
<?php
$i=1;
while($i<2){
?>
<tr>
<td>
<input type="hidden" name="prdid[]" id="prd_id<?php echo $i; ?>" />
</td>
<td>
<input type="text" name="prdcost[]" id="prd_cost<?php echo $i; ?>" value="0" disabled="disabled" style="color:#333;" />
</td>
<td>
<input type="text" name="prdquentity[]" id="prd_quentity<?php echo $i; ?>" tabindex="<?php echo 3+($i*5);?>" onKeyUp="calprice1(this.value,'<?php echo $i; ?>');" value="1" />
</td>
<td>
<input type="text" name="prddamount[]" tabindex="<?php echo 5+($i*5);?>" readonly="true" id="prd_damount<?php echo $i; ?>" onKeyUp="calprice2(this.value,'<?php echo $i; ?>');" />
</td>
<td id="readonly">
<input readonly="readonly" name="prdprice[]" id="prd_price<?php echo $i; ?>" value="0" />
</td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table><!--#invoices-product-detail-->
Now under that I have a button called Add a new line:
<input type="button" onClick="createRow();" value="Add a new line"></span>
in js file I have the createRow() function like this
function createRow() {
var newlineno = document.forms[0].elements["prdprice[]"].length;
newlineno++;
var row = document.createElement('tr');
var col1 = document.createElement('td');
var col2 = document.createElement('td');
var col3 = document.createElement('td');
var col4 = document.createElement('td');
var col5 = document.createElement('td');
var col6 = document.createElement('td');
var col7 = document.createElement('td');
row.appendChild(col1);
row.appendChild(col2);
row.appendChild(col3);
row.appendChild(col4);
row.appendChild(col5);
row.appendChild(col6);
row.appendChild(col7);
col1.innerHTML = "<input type=\"hidden\" name=\"prdid[]\" id=\"prd_id"+newlineno+"\" /><input type=\"text\" name=\"prdname[]\" id=\"prd_name"+newlineno+"\";
col2.innerHTML = "<input type=\"text\" disabled=\"disabled\" name=\"prddesc[]\" id=\"prd_desc"+newlineno+"\" />";
col3.innerHTML = "<input type=\"text\" disabled=\"disabled\" name=\"prdcost[]\" id=\"prd_cost"+newlineno+"\" value=\"0\" />";
col4.innerHTML = "<input type=\"text\" name=\"prdquentity[]\" id=\"prd_quentity"+newlineno+"\" onKeyUp=\"calprice1(this.value,'"+newlineno+"');\" value=\"1\" />";
col5.innerHTML = "<select name=\"prddtype[]\" class=\"discount-type\" id=\"prd_dtype"+newlineno+"\" >"+document.getElementById("prd_dtype0").innerHTML+"</select>";
col6.innerHTML = "<input type=\"text\" name=\"prddamount[]\" id=\"prd_damount"+newlineno+"\" onKeyUp=\"calprice2(this.value,'"+newlineno+"');\" />";
col7.innerHTML = "<input type=\"text\" name=\"prdprice[]\" id=\"prd_price"+newlineno+"\" class=\"price-input-text\" disabled=\"disabled\" value=\"0\" />";
var table = document.getElementById("tableToModify"); // find table to append to
table.appendChild(row); // append row to table
}
Now here everything is fine. As per js I can easily add another row. But when I checked the id of input fields I saw that the first row (default one) is showing <input type="text id="prd_name1"> which one is fine. But when I clicked to the add a new line and the new created line id was <input type="text" id="prd_nameNaN">. But here I want the id should be like <input type="text" id="prd_name2"> and for 3rd row <input type="text" id="prd_name3"> like so on. Here for every new created row the number of row will be added to every field id. Here can someone kindly tell me why this issue is here? Any help and suggestions are highly appreciable.
document.forms[0].elements["prdprice[]"] will only return a single DOM element if there is only one instance on the page, therefore calling .length on this will return undefined:
var newlineno = document.forms[0].elements["prdprice[]"].length; // Undefined
newlineno++; // NaN
Use querySelectorAll if possible instead:
var newlineno = document.querySelectorAll("[name='prdprice[]']").length
See this fiddle demonstrating three inputs: http://jsfiddle.net/Blade0rz/3Eyba/
And this one demonstrating one: http://jsfiddle.net/Blade0rz/kqakC/
It appears that the variable newlineno is not a Number, that's what NaN stands for. check that the following line creates an actual number:
var newlineno = document.forms[0].elements["prdprice[]"].length;
newlineno++;
console.log(newlineno); // open Firefox' Firebug or a similar tool to see the output of this variable
All you have to do id add a parseInt() function around the newlineno variable to convert it into an integer value.I had the same problem and and it got solved like this
var size = parseInt(document.getElementById(disease+"members").value);
and probably you should use .value instead of .length
example:
var newlineno = parseInt(document.getElementById("prdprice").value);
or make some changes to the above example and it might work for you.