Changing value in html table dynamically - javascript

I have an html table where i retrieve data from a database using PHP. The table is quite simple, i have three fields: Name, Quantity and Price. At the end of the table i have an additional field, Subtot, that shows the final cost (SumOfAllItems(Quantity*Price)).
I need to be able to change the "Quantity" value in each row and the "Subtot" should update accordingly. I also need to be able to set min/max value the user can use to update the cell.
I was thinking to add something like a button or any kind of list/input by the "Quantity" value in each row.
I think i need to use javascript but i am not sure, any suggestion is welcome.
Following my code.
Thanks
<table>
<tbody>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price<th>
</tr>
<?php
while($row2 = $result->fetch_assoc())
{?>
<tr>
<td><?php echo $row2["Name"] ?></td>
<td><?php echo $row2["Quantity"] ?></td>
<td><?php echo $row2["Price"]?></td>
</tr>
<?php
$subtot = $subtot + ($row2["Price"] * $row2["Quantity"])
} ?>
<td></td>
<td><b>Subtot.</b></td>
<td><b><?php echo $subtot2 ." Euro"; $tot = $subtot1 + $subtot2;?> </b></td>
</tbody>
</table>

The following should work, however i do not recommend this method (any method btw) without any validation on server side.
You need this on top of your php file:
<?php
$total = 0;
Then your table like:
<table>
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price<th>
</tr>
</thead>
<tbody>
<?php while($row2 = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row2['name'] ?></td>
<td><input class="row" min="0" onchange="myFunction()" data-price="<?php echo $row2['price'] ?>" type="number" value="<?php echo $row2['quantity'] ?>"/></td>
<td><?php echo $row2['price'] ?></td>
</tr>
<?php
$total += $row2['price'] * $row2['quantity'];
}
?>
<td></td>
<td>
<b>Subtot.</b>
</td>
<td>
<b id="total"><?php echo $total; ?></b>
</td>
</tbody>
</table>
And you need the following script tag:
<script>
function myFunction(){
var total = 0;
var elements = document.getElementsByClassName("row");
for(var i = 0; i < elements.length; i++) {
total += elements[i].value * elements[i].dataset.price;
}
var totalEl = document.getElementById("total");
totalEl.innerHTML = total;
}
</script>
Again.. this is a very simple solution, but it should work.

Related

After the click does not appear in bold

I created an internal email system within the project. When I receive a new message the column with the subject name in my table is bolded to inform that the message has not yet been read.
code:
<?php
while($row = mysqli_fetch_array($result))
{
?>
<section id="s1">
<div class="div1" id="minhaDiv" style="float: left;">
<table class="table table-bordered">
<tr>
<th width="20%">De</th>
<th width="60%">Assunto</th>
<th width="10%">Prioridade</th>
<th width="10%">Recebido</th>
</tr>
<tr>
<th width="10%" colspan=4>Recebido: <?php echo $row["Data"]; ?></th>
</tr>
<tr>
<td><?php echo $row["De"]; ?></td>
<td class="td-info view_data" id="<?php echo $row["Id"]; ?>" data-toggle="modal" href="#dataModal" width="20%" style="font-weight:bold" onclick="this.style['font-weight'] ='normal'"><?php echo $row["Assunto"]; ?></td>
<td><?php echo $row["Prioridade"]; ?></td>
<td><?php echo $row["Hora"]; ?></td>
</tr>
<tr>
<?php
}
?>
</table>
</div>
</section>
In the image, which is surrounded by green already clicked to read, the red has not yet vliquei to read, so it is bold:
I use this code to put bold inside the td:
width="20%" style="font-weight:bold" onclick="this.style['font-weight'] ='normal'"
The problem is that if you refresh the page, even after reading the messages, they come back in bold and should not. After clicking once, they can not be left in bold
Solution to achieve the condition.
I created a Status field in the database table, where 1 is unread message and 0 message is read, now is to create the condition in td with if. In the javascript with which I open the modal I made the following change:
$('.td-info').click(function(){
var item_id = $(this).attr("id");
var status = $(this).attr("Status");
$.ajax({
url:"./fetchRAD",
method: "POST",
data:{item_id:item_id, status:status},
success:function(data){
}
});
});
In td I indicated the id of the record in the id of td:
id="<?php echo $row["Id"]; ?>"
file with php:
if(isset($_POST["item_id"]))
{
$query = "Update centrodb.Alertas SET Status = '0' WHERE Id = '".$_POST["item_id"]."'";
$result = mysqli_query($conn, $query);
}
Pata check in the td we put like this:
width="20%" <?php echo $row["Status"] == '1'?' style="font-weight:bold" ':' style="font-weight:normal" '?>
td complete:
<td class="td-info view_data" id="<?php echo $row["Id"]; ?>" data-toggle="modal" href="#dataModal" width="20%" <?php echo $row["Status"] == '1'?' style="font-weight:bold" ':' style="font-weight:normal" '?>><?php echo $row["Assunto"]; ?></td>

outlook mail window with pre populated to sender box not working

errors i get
I have a table that contains details one of this being emails. When i click a link i have outlook mail opening but i want to take the email of that row in the table and put it into the 'to' part of the email. Below i have code for what i am currently doing.
the code below displays the data from my database in a table format
<table class="table table-striped custab">
<thead>
<tr>
<th> </th>
<th>Booking ID</th>
<th> Name</th>
<th>Email</th>
<th>Date</th>
<th>time</th>
<th>No. of guests</th>
<th>Booking Reason</th>
<th>Comments</th>
<th width="110" class="ac">Approved?</th>
</tr>
<thead>
<!-- php function to only select the bookings that have not yet been approved/rejected -->
<?php
include 'config.php';
$select = "SELECT * FROM `booking` WHERE `status`IS NULL ";
$result = $conn->query($select);
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="checkbox" class="checkbox" /></td>
<td><?php echo $row['customer_ID'] ?></td>
<td><?php echo $row['Name'] ?></td>
<td><?php echo $row['Email'] ?></td>
<td><?php echo $row['booking_date'] ?></td>
<td><?php echo $row['booking_time'] ?></td>
<td><?php echo $row['attendee_no'] ?></td>
<td><?php echo $row['booking_reason'] ?></td>
<td><?php echo $row['comments'] ?></td>
<td>
Email this Codesnippet</a>
</td>
</tr>
<?php
}
?>
</table>
The function below gets the pop up to display for outlook mail
<script type="text/javascript"> TriggerOutlook(Email)
{
var $to = 'Email';
var body = "your booking has been approved";
<!-- var body = escape(window.document.title + String.fromCharCode(13)+ window.location.href); --->
var subject = "Your booking request";
window.location.href = "mailto:?body="+body+"&to="+$to+"&subject="+subject;
}
</script>
if i put in an email manually into the var $to = the outlook pop up works however if i try to take the email from the table it doesnt, can anyone help me out to identity where i am going wrong? Thanks!
1 You don't need the PHP $ declaration for variables, thus:
var $to = 'Email';
should be:
var to = 'Email';
more descriptive variables could make future updates easier:
var toAddr = 'Email';
2 Your JavaScript function should be preceded with the function tag
<script type="text/javascript"> TriggerOutlook(Email)
{
changes to:
<script type="text/javascript">
function TriggerOutlook(Email){
3 Use a button rather than link
Replace
Email this Codesnippet</a>
With
<button
onclick="TriggerOutlook(<?php echo $row['Email'];?>)"
value="submit"
>Email this Codesnippet</button>

How to use jQuery POST instead of html form to delete table entry

I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>

hide/show columns $row depending checkbox or radio

I need to create a checkbox that hide the rows that contain MULTIPLE in CARS value from a CRUD.
This is the part where I need to implement the checkbox:
<body>
<?php while($row = $resultado->fetch_array(MYSQLI_ASSOC)) { ; ?>
<form name="form">
Hiden Multiple: <input type="checkbox" id="ck"
***onclick="hide if $row['Cars']= Multiple, if not show :D "***/>
</form>
<table id="tabla" border="1">
<tr>
<td><?php echo $row['ID']; ?></td>
</tr>
<tr>
<td><?php echo $row['Name']; ?></td>
</tr>
<tr>
<td><?php echo $row['Years']; ?></td>
</tr>
<tr>
<td><?php echo $row['Cars']; ?></td>
</tr>
</table>
</body>
I can point you in the direction, but you need to code it yourself.
PHP / HTML: you need one form, so place your outside your while-loop
PHP / HTML: add an css class to the table when condition "$row['Cars'] == 'Multiple'" is true eq:
Javascript: hide / show elements with class "has_multiple_cars" when checking/unchecking the checkbox.
Yes, only found this java and work but with de number of the line:
<script type="text/javascript">
function ocultarFila(numFila) {
var form = document.form;
fila = document.getElementById('tabla').getElementsByTagName('tr')[numFila];
if(form.ck.checked == true) {
fila.style.display = 'none';
} else {
fila.style.display = '';
}
}
</script>
</head>
<body>
<?php while($row = $resultado->fetch_array(MYSQLI_ASSOC)) { ;
?>
<form name="form">
Hiden Multiple: <input type="checkbox" id="ck" onclick="ocultarFila(1)"/>
</form>
Can make a condition for me? I'm starting to program and I do not find the right sentence, thanks!

Update checked state of checkbox in table header on page load

I have a table with a checkbox at the top of the first column to allow the user to select all items in the table and perform an AJAX script. I'm using PHP to generate the html table from a database query - I'd like to set the checked value for the header checkbox if all items in the table are also checked for the same column.
In the PHP file I'm setting up the table and the header rows first, then doing a foreach loop to create the table rows from the found records. I could add a counter along the way to track how many rows are checked, but as this is happening after the table header I can't see a way to subsequently update the header row? Unless this could be done via Javascript?
Here's my PHP page that generates the table:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th><input type="checkbox" class="select-all checkbox" name="select-all" /> </th>
<th class="text-center" scope="col">Product ID</th>
<th class="text-center" scope="col">Description</th>
</thead>
<tbody>
$found = $result->getFoundSetCount();
foreach($records as $record) {
$productID = $record->getField('productID');
if (!in_array($productID, $_SESSION['selectedProductIDs'])) {
$checked = '';
} else {
$checked = ' checked';
}
?>
<tr class="" id="<?php echo $recid ?>">
<td id="<?php echo $productID; ?>"><input type="checkbox" class="select-item checkbox" name="select-item" value="<?php echo $productID; ?>" <?php echo $checked; ?>></td>
<td><?php echo $productID; ?></td>
<td><?php echo $record->getField('Description'); ?></td>
</tr>
} // foreach
i did not test this code, but i think is what do you search
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
var allAreChecked = true;
$("table > tbody > tr > td > input[type=checkbox]").each(function(){
if(! $(this).is(':checked'))
allAreChecked = false;
});
if(allAreChecked === true){
$("table > thead > tr > th > input[type=checkbox]").prop('checked', true);
}
});
</script>
simple do the trick with string concatenation like below
1st : First run the foreach loop and concatenate all tr as a string .
2nd : Outside the foreach loop Set the $check_all_button=true; in foreach loop check any row is not checked means set the variable to false.
3rd : After all this concatenate the table header part with another variable . based on $check_all_button variable value check the checkbox .
4th : Finally echo the both variables . to render the html table .
<?php
$found = $result->getFoundSetCount();
$table_tr='';
$check_all_button=true;
foreach($records as $record)
{
$productID = $record->getField('productID');
if (!in_array($productID, $_SESSION['selectedProductIDs'])) {
$checked = '';
$check_all_button=false;
} else {
$checked = ' checked';
}
$table_tr.="<tr class='' id='<?php echo $recid ?>'>
<td id='<?php echo $productID; ?>'><input type='checkbox' class='select-item checkbox' name='select-item' value='<?php echo $productID; ?>' <?php echo $checked; ?>></td>
<td><?php echo $productID; ?></td>
<td><?php echo $record->getField('Description'); ?></td></tr> ";
<?php
}
$check_all_button=true;
$table_and_head='';
$table_and_head.="<table class='table table-condensed table-striped table-bordered'>
<thead>
<th><input type='checkbox' class='select-all checkbox' name='select-all'";
if($check_all_button==true){ $table_and_head.=' checked'; }
$table_and_head.=" /> </th>
<th class='text-center' scope='col'>Product ID</th>
<th class='text-center' scope='col'>Description</th>
</thead>
<tbody> </tbody> </table>";
echo $table_and_head;
echo $table_tr;
?>

Categories

Resources