This is my code
<html>
<head>
<title>
Aplikasi KRS
</title>
</head>
<body>
<p>IPK : 1.xx</p>
<form name="formTes" method="post">
<script>
function cekKrs()
{
var jum_sks = 0;
for(var i=0; i<7; i++)
{
if(document.formTes.elements[i].checked)
jum_sks += mataKuliah;
}
document.formTes.fieldJumlah.value = jum_sks;
if(jum_sks > 15)
{
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
}
}
function cekKirim()
{
if(document.formTes.fieldJumlah.value > 15)
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
else
window.location.href = "tesform.html";
}
</script>
<table border="2">
<tr><th>Kode</th><th>Mata Kuliah</th><th>SKS</th><th><Pilihan/th></tr>
<?php
include "koneksi.php";
$sql = "SELECT * FROM mata_kul";
$query = $con->query($sql);
while($mataKuliah = $query->fetch_array())
{
echo "<tr><td>". $mataKuliah['kodeMK'] ."</td>";
echo "<td>". $mataKuliah['namaMK'] ."</td>";
echo "<td>". $mataKuliah['sks'] ."</td>";
echo "<script>var mataKuliah= ".$mataKuliah['sks']."</script>";
echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs()'></td>";
}
?>
<tr><td colspan="2" align="right">Jumlah SKS</td>
<td colspan="2"><input size="3" value="0" name="fieldJumlah" type="text" readonly="readonly"></td></tr></table>
<br>
<input type="button" name="tombolKirim" value="Kirim" onclick="cekKirim()">
</form>
</body>
</html>
My question is
"Why when i click checklist it show the last value of sks in jumlah SKS, not the sks checked value i click ? like when i click checklist which have value of 2 in sks it should show 2 not 8 in jumlah SKS"
Here's the image
Can you tell me where did i go wrong ? I'm still new
I guess you need send the checkbox obj as param to cekKrs() , and in function cekKrs evaluates if obj is checked to + or - the obj.value from total
Try this DEMO
HTML ( draft )
<table>
<!-- while($mataKuliah = $query->fetch_array())
{ -->
<tr>
<!-- echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs(this)' value='".$mataKuliah['sks']."'></td>"; // PHP -->
<td><input type='checkbox' onclick='cekKrs(this)' value='1'>1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='2'>2</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='3'>3</td>
</tr>
<!-- } -->
</table>
<input size="3" value="0" name="fieldJumlah" id='fieldJumlah' type="text" readonly="readonly">
onclick='cekKrs(this)' sends checkbox obj , and you keep the mataKuliah's value inside the checkbox value
JS
function cekKrs(chkObj)
{
//Get current total
var jum_sks = parseInt(document.getElementById('fieldJumlah').value);
//Get checkbox value clicked
var mataKuliah = parseInt(chkObj.value);
//Evaluate check to + or -
if(!chkObj.checked)
{
mataKuliah = (mataKuliah * -1)
}
jum_sks += mataKuliah;
//Set new total
document.getElementById('fieldJumlah').value = jum_sks;
}
Related
I've been having issues trying to call a php script via javascript when the user changes a value in the "Assigned To Group" selection. Which is ultimately supposed to change the option list of, a not yet created, "Assign to User" selection.
I keep getting an error saying that it doesn't recognize the function's name. When I tried running a simple value change and alert to verify it could get the values, it recognized it and it updated accordingly. When I added the Ajax command is when it started not recognizing it. I'm sure I'm probably just using incorrectly, somehow, sense I've never used ajax before. But from the samples I've seen, it seems fairly straight forward.
Error: Uncaught ReferenceError: onChangeAssignedGroup is not defined at HTMLSelectElement.onchange
<?php
include('classes/class.User.php');
include('classes/class.Role.php');
include('classes/class.User_Role.php');
include('constants.php');
session_start();
?>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function onChangeAssignedGroup() {
var new_assigned_to_role_id = document.getElementById("option_list_assigned_to_role_id").value;
document.getElementById("assignedGroupId").innerHTML = "You selected: " + new_assigned_to_role_id;
alert(new_assigned_to_role_id);
$.ajax({
method: "POST",
url: "ticket_details.php",
data:{
ticket_id:$_POST['ticket_id'];
creator_user_id:$_POST['creator_user_id'];
creator_user_name:$_POST['creator_user_name'];
status:$_POST['status'];
priority:$_POST['priority'];
title:$_POST['title'];
assigned_to_role_id:new_assigned_to_role_id;
assigned_to_role_name:"";
assigned_to_user_id:$_POST['assigned_to_user_id'];
assigned_to_user_name:$_POST['assigned_to_user_name'];
},
success: function () {
alert('form was submitted');
}
});
}
</script>
</head>
<body>
<p>Return to Tickets</p>
<?php
if(isset($_POST['submit']) or isset($_POST['submit_new_comment']) or isset($_POST['submit_update_ticket'])){
$ticket_id = $_POST['ticket_id'];
$creator_user_id = $_POST['creator_user_id'];
$creator_user_name = $_POST['creator_user_name'];
$status = $_POST['status'];
$priority = $_POST['priority'];
$title = $_POST['title'];
$assigned_to_role_id = $_POST['assigned_to_role_id'];
$assigned_to_role_name = $_POST['assigned_to_role_name'];
$assigned_to_user_id = $_POST['assigned_to_user_id'];
$assigned_to_user_name = $_POST['assigned_to_user_name'];
//connect to database
include("database_connection.php");
//handle update to ticket
if(isset($_POST['submit_update_ticket'])){
$update = $mysqli->query("UPDATE `ticket` SET `status` = '$status', `priority` = '$priority',
`assigned_to_role_id` = '$assigned_to_role_id', `assigned_to_role_name` = '$assigned_to_role_name',
`assigned_to_user_id` = '$assigned_to_user_id', `assigned_to_user_name` = '$assigned_to_user_name'
WHERE `ticket`.`id` = $ticket_id");
if(!$update){
echo"<p>".$mysqli->error."</p>";
}
}
//handle new comment
if(isset($_POST['submit_new_comment'])){
$new_comment = $_POST['new_comment'];
$current_id = $_SESSION['user']->getId();
$current_username = $_SESSION['user']->getUsername();
//sanitize data
$new_comment = $mysqli->real_escape_string($new_comment);
unset($_POST['submit_new_comment']);
//insert new comment into database.
$insert = $mysqli->query("INSERT INTO ticket_comment (ticket_id, user_id, user_name, text) VALUES ('$ticket_id', '$current_id', '$current_username', '$new_comment')");
if(!$insert){
echo"<p>".$mysqli->error."</p>";
}
}
//include arrays for converting values returned
include("value_maps.php");
echo "<p id='assignedGroupId'></p>";
echo "<p>role id:".$assigned_to_role_id."</p>";
echo "<p>role name:".$assigned_to_role_name."</p>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles())){
echo "<p>you have this role.</p>";
} else {
echo "<p>you don't have this role.</p>";
}
print_r($_SESSION['user']->getRoles());
echo"
<form action='' method='post'>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Ticket ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
<th>Assigned To Group</th>
<th>Assigned To User</th>
</tr>
<tr>
<td>$ticket_id</td>
<td>$title</td>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles()) or in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select name='status'>";
$status_index = 0;
foreach($status_array as $status_choice){
if($status == $status_index){
echo "<option value='". $status_index."' selected>". $status_choice ."</option>";
} else {
echo "<option value='". $status_index."'>". $status_choice ."</option>";
}
$status_index++;
}
echo "</select></th>";
echo "<td><select name='priority'>";
$priority_index = 0;
foreach($priority_array as $priority_choice){
if($priority == $priority_index){
echo "<option value='". $priority_index."' selected>". $priority_choice ."</option>";
} else {
echo "<option value='". $priority_index."'>". $priority_choice ."</option>";
}
$priority_index++;
}
echo "</select></th>";
} else {
echo "<td>".$status_array[$status]."</th>";
echo "<td>".$priority_array[$priority]."</th>";
}
if(in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select id='option_list_assigned_to_role_id' name='assigned_to_role' onchange='onChangeAssignedGroup()'>";
foreach($_SESSION['roles'] as $assigned_to_role_choice){
if($assigned_to_role_id == $assigned_to_role_choice->getId()){
echo "<option value='". $assigned_to_role_choice->getId()."' selected>". $assigned_to_role_choice->getName() ."</option>";
} else {
echo "<option value='". $assigned_to_role_choice->getId()."'>". $assigned_to_role_choice->getName() ."</option>";
}
}
echo "</select></td>";
} else {
echo "<td>$assigned_to_role_name</td>";
echo "<td>$assigned_to_user_name</td>";
}
echo"
</tr>
<tr>
<td colspan='5'></td>
<td><input type='submit' name='submit_update_ticket' value='Update Ticket Details' required></td>
</tr>
</table>
</form>
";
//get back ticket details
$results = $mysqli->query("SELECT `id`,`ticket_id`,`user_id`,`user_name`,`text`,`create_date`,`modify_date` FROM `ticket_comment` WHERE `ticket_id` = ".$ticket_id." ORDER BY `create_date`");
//if insert was successful
if($results){
//header('location:registration_email_sent.php');
if ($results->num_rows > 0){
echo "
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Username</th>
<th>Comment</th>
</tr>
";
while($row = $results->fetch_row()){
echo"
<tr>
<td>".$row[3].": </td>
<td>".$row[4]."</td>
</tr>";
}
} else {
echo "<p>No comments found. </p>";
}
}
$mysqli->close();
echo"
<form method='post' action=''>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='status' value='$status'>
<input type='hidden' name='priority' value='$priority'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>New Comment</th>
<th><input type='submit' name='submit_new_comment' value='Post New Comment'></th>
</tr>
<tr>
<td colspan='2'><textarea name='new_comment' rows='10' cols='30' placeholder='New Comment Here' required></textarea></td>
</tr>
</table>
</form>
";
}
?>
</body>
</html>
In the data object in your ajax request, you need to replace the semicolons with commas.
You should also always use prepared statements to interact with the database.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've got some code where I have to input my contact data from client, and output data from MySQL database which creates new rows in table
Also there's additional function which has to be inside the code - but I've no idea how to handle this problem. I have to count the amount of element pieces x their weight in real-time to show the client the total weight the order is going to have.
The problem is I don't know how to make the client see it whenever they change the value of Pieces in <input>.
Lastly, the data from the form and table has to be sent to employee via email.
PHP Code:
<html>
<head>
<meta charset="utf-8" />
<meta name="calculator" content="width=device-width, initial-scale=1"/>
<title>Test</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<h1>TEST</h1>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
<input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<table class="table-responsive" border="1">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
}
} else {
echo "0 Results";
}
mysqli_close($connection);
?>
</tbody>
</table>
<!-- Counting all needed atributes -->
<div id="totalWeight">totalWeight</div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
</html>
JavaScript Code
<script type="text/javascript">
document.addEventListener(function()
input.OnChange = calculateForm();
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
totalWeight += sumWeight;
}
});
document.write(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
Updated
Well it doesn't work again, no errors, just doesn't multiply
I think the problem might be with transporting data from table/database into the variable, any solution?
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
echo "></input>";
# echo "<tr><td>".$row["id"].'';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
<!-- Counting all needed atributes -->
<div id="totalWeight"></div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
Overall there are quite a few issues with your code, which can be summarised as problems with
invalid HTML (e.g. duplicate IDs, incorrectly written input element, un-closed table rows, un-closed data attributes)
over-complicated HTML
typing or case errors (e.g. W instead of w)
incorrect CSS selectors in the JavaScript
lack of initial default data (e.g. if there are no numbers in any one of the input boxes, the calculation will fail because trying to add a blank value to another number results in NaN (Not a Number)
calculation did not run when page loads, so data is missing until the user changes something (which is no use, if they want to see the current weight before changing any values)
This client-side demo demonstrates the HTML you need to get your PHP to produce, and the correct JavaScript / jQuery code in order to do the calculations and display the results:
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
border-collapse:collapse;
}
td
{
border: solid 1px black;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
<td>Nr. 14536</td>
<td>Test 1</td>
<td>3 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
<td>Nr. 23431</td>
<td>Test 2</td>
<td>15 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
<td>Nr. 33125</td>
<td>Test 3</td>
<td>4 kg</td>
<td class='sum-weight2'></td>
</tr>
</tbody>
</table>
Total Weight: <span id="totalWeight"></span>
Remember you need to move the focus from the textbox to another element (using mouse or tab key) before the "change" event will fire. (It will also run if you use the up/down buttons on the input box.)
So this means, as well as editing the JavaScript as I've shown, you need to alter the PHP so it outputs the HTML table rows with the structure and data I've demonstrated above.
This should work:
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
Resolution:
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="Email" class="form-contact" required><br>
<input id="Country" type="text" placeholder="49" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="Tel" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class=".table-responsive">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='0' min='0' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
</script>
<!-- Counting all needed atributes -->
Total Weight: <span id="totalWeight"></span>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
FYI- I am making a timesheet project using PHP and MySQL
I am new to PHP, I tried to use PHP make HTML table rows and assign them row id, but the problem is that my table is displaying a large number of rows, so I made a javascript filter to display only rows which match with the filter values
But the problem is I don't how to use row id and then use their values to get compared with the javascript variable and based on match its CSS property is set to display (if matched) or hide (if not matched).
Is there any other way to do this?
Here is Filter Section.
<div class='row'>
<div class='col'>
<label>Select Filters:</label>
</div>
</div>
<div class='row'>
<div class='col'>
<div class='filter'>
<label>EmpID:</label>
<select id='empid_select'>
<option value='' >select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `EmpID`, `Name` FROM `employee_data` ORDER BY `EmpID` ');
if($stmt->execute()){
$stmt->bind_result($empid, $empname);
while($stmt->fetch()){
echo "<option value='$empid'>$empid - $empname</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
$stmt->close();
?>
</select>
<label>Project Code:</label>
<select id='projectcode_select'>
<option value=''>Select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `Projectcode`, `Title` FROM `Projectcodetbl` ORDER BY `Projectcode` ASC ');
if($stmt->execute()){
$stmt->bind_result($projectcode, $title);
while($stmt->fetch()){
echo "<option value='$projectcode'>$projectcode - $title</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
?>
</select>
<label>Start Date: </label>
<input type='date' name='startdate-filter' id='startdate-filter' >
<label>End Date: </label>
<input type='date' name='enddate-filter' id='enddate-filter' >
<button name='notseen-entries-filter-button' id='notseen-entries-filter-button'>Apply</button>
</div>
</div>
</div>
Here is my script to get value form the filter section.
<script>
$(document).ready(function(){
$('[name="notseen-entries-filter-button"]').click(function(e){
var empid = $('#empid_select option:selected').val();
var projectcode = $('#projectcode_select option:selected').val();
var startdate = $('#startdate-filter').val();
var enddate = $('#enddate-filter').val();
alert("Filter rows with values EmpID: "+empid+", ProjectCode: "+projectcode+", StartDate: "+startdate+", EndDate: "+enddate);
});
});
</script>
PHP Function for displaying the table heading
function displayTableHeading(){
echo "
<form action='selected.php' method='post'>
<table border='1' cellpadding='10' cellspacing='0'>
<tr>
<th colspan='13'><button type='submit' class='btn btn-outline-primary' style='border-radius: 3px;'><i class='fas fa-edit' style='margin-right:10px;'></i>Update</button>
</tr>
<tr>
<th>Row</th>
<th>EmpID - Name</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hrs</th>
<th>Project Code</th>
<th>Task Performed</th>
<th>Invoice Num</th>
<th colspan=3>Status</th>
</tr>";
}
PHP Function for displaying the table rows.
//Webpage Table Row
function displayTableRow($row, $i, $empid){
$notBillable = intval( $row['Status'] )==1 ? 'checked' : '';
$billablePlusNotInvoiced = intval( $row['Status'] )==2 ? 'checked' : '';
$billablePlusInvoiced = intval( $row['Status'] )==3 ? 'checked' : '';
printf("
<!-- record: %d -->
<tr id='%d'>
<td><input type='text' size='1' value='%d' ></td>
<td><input type='text' size='10' name='empid[]' value='%s'></td>
<td><input type='text' size='7' name='date[]' value='%s' ></td>
<td><input type='text' size='5' name='stime[]' value='%s' ></td>
<td><input type='text' size='5' name='etime[]' value='%s' ></td>
<td><input type='text' size='1' name='hours[]' value='%s' ></td>
<td><b><input type='text' size='9' name='projectcode[]' value='%s' ></b></td>
<td><input type='text' size='30' name='taskperformed[]' value='%s' ></td>
<td><input type='text' size='8' name='invoicenum[]' value='%s' ></td>
<td><input type='radio' name='status_{$i}[]' value='1' %s/>NB</td>
<td><input type='radio' name='status_{$i}[]' value='2' %s/>B+NI</td>
<td><input type='radio' name='status_{$i}[]' value='3' %s/>B+I</td>
<input type='hidden' name='modifieddate[]' value='%s'>
</tr>",
$i,$i,$i,
getEmpNameById($empid),
$row['Date'],
$row['StartTime'],
$row['EndTime'],
$row['NoOfHours'],
$row['ProjectCode'],
$row['TaskPerformed'],
$row['InvoiceNumber'],
$notBillable,
$billablePlusNotInvoiced,
$billablePlusInvoiced,
$row['ModifiedDate']
);
}
PHP code for calling above function and displaying the HTML table.
$sumNoOfHours = 0.0;
displayTableHeading();
$i=1;
foreach($empid_array as $code){
//split the $code variable to get the emp id
$codearr = explode(" - ", $code);
$empid = $codearr[0];
$selectSql = "SELECT * FROM `mastertbl` WHERE EmpID = '$empid' AND Status = 0 ORDER BY Date DESC, ModifiedDate DESC";
$result = mysqli_query($conn, $selectSql) or die( mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$sumNoOfHours = $sumNoOfHours + $row['NoOfHours'];
displayTableRow($row, $i, $empid);
$i++;
}
}
I have a dynamic table form input form which you can add/remove rows as you like. As someone who doesn't have much experience, I'm stuck on how to save those input into the mySQL database.
Here's what the input.php looks like
<form action="insert.php" method="post">
<div class="box-body no-padding">
<table class="table table-bordered">
<tr>
<th>Item</th>
<th>#</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
<tr>
<td><input type="text" id="item" name="item"></td>
<td><input type="text" id="no" name="no"disabled></td>
<td><input type="number" id="qty" name="qty"></td>
<td><input type="number" id="price" name="price"></td>
<td><input type="number" id="total" name ="total" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
</table>
</div>
<div class="box-body">
<div class="button-group">
<i class="fa fa-plus-circle"></i> Add Item
</div>
</div>
<div class="box-footer">
<div class="button-group pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
And here is the JS (jQuery) code that I use to add/remove rows
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function(){
$(document).ready(function(){
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item'></td>";
var no = "<td><input type='text' id='no' disabled></td>";
var qty = "<td><input type='number' id='qty'></td>";
var price = "<td><input type='number' id='price'></td>";
var total = "<td><input type='number' id='total' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
$(".table").on('click', '.remove-row', function(){
$(this).closest("tr").remove();
});
});
});
</script>
Here's what the page looks like:
input page
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db", $connection);
if(isset($_POST['submit'])){
$item = $_POST['item'];
$no = $_POST['no'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$query = mysql_query("insert into table(item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
?>
I know the insert.php won't work for my case because I need to input it as arrays. The thing is:
1. I don't know how to implement the front end so I won't have duplicate id/names when I click "Add Item"
2. I don't know how to insert the arrays (that I don't know to create) to the mysql.
I'd like to know how can I implement the save button in my case. Thank's for your help.
First, please research the mysql_* functions. They should no longer be used because they can lead to SQL injection security issues. Use mysqli_* instead or a DB layer like PDO.
Second, if you append "[]" to your input tag names then PHP will receive the data as arrays and you can loop through it in your insert.php.
<tr>
<td><input type="text" id="item" name="item[]"></td>
<td><input type="text" id="no" name="no[]" disabled></td>
<td><input type="number" id="qty" name="qty[]"></td>
<td><input type="number" id="price" name="price[]"></td>
<td><input type="number" id="total" name="total[]" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
And be sure your javascript code also adds the name attribute:
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item' name='item[]'></td>";
var no = "<td><input type='text' id='no' name='no[]' disabled></td>";
var qty = "<td><input type='number' id='qty' name='qty[]'></td>";
var price = "<td><input type='number' id='price' name='price[]'></td>";
var total = "<td><input type='number' id='total' name='total[]' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
Then in PHP you can have:
<?php
$connection = mysqli_connect("localhost", "root", "", "db");
if(isset($_POST['submit'])){
$rowCount = count($_POST['item']);
// Note that this assumes all the variables will correctly be submitted as arrays of the same length. For completeness and robustness you could add a !empty check for each value.
for ($i = 0; $i < $rowCount; $i++) {
$item = $_POST['item'][$i];
$no = $_POST['no'][$i];
$qty = $_POST['qty'][$i];
$price = $_POST['price'][$i];
$query = mysqli_query($connection, "insert into `table` (item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
}
?>
I want to do what I did in the snippet but as an array. What do I mean by this. Lets say a user wants to add another row to the example in the snippet. The code should run both and calculate the total from both rows. There can be new rows added that is why im saying im trying to do this as an array. I'm trying to do something like excel does with cells that add the data depending on the change of a cell but in a much simpler manner just addition and only specified cells.
How would I do this?
this is the code that I have that I want to add this functionality to:
index.php
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
/* this function would also add the prices to the table*/
var first_name = $('#first_name').text();
var last_name = $('#last_name').text();
if(first_name == '')
{
alert("Enter First Name");
return false;
}
if(last_name == '')
{
alert("Enter Last Name");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{first_name:first_name, last_name:last_name},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$output = '';
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>
<td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="first_name" contenteditable></td>
<td id="last_name" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
$(document).ready(function() {
// functions assigned to onchange properties
document.getElementById('price').onchange = function() {
// access form and value properties via this (keyword)
var form = this.form;
var total = parseFloat(this.value) + parseFloat(form.elements['aditional_price'].value);
form.elements['total'].value = formatDecimal(total);
};
document.getElementById('aditional_price').onchange = function() {
// access form and value properties via this (keyword)
var form = this.form;
var total = parseFloat(this.value) + parseFloat(form.elements['price'].value);
form.elements['total'].value = formatDecimal(total);
};
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round(parseFloat(val) * Math.pow(10, n));
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0, pt) + "." + str.slice(pt);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="form1" class="form1" name="form1">
<fieldset>
<p>
Price
<input name="price" id="price" size="4" value="0" />+ Aditional Price
<input name="aditional_price" id="aditional_price" value="0" size="4" />
<br/>
<!-- new row added
<br/>
Price
<input name="price" id="price" size="4" value="0" />+ Aditional Price
<input name="aditional_price" id="aditional_price" value="0" size="4"/>
<br/>
-->
<br/>
<label>Total: $
<input type="text" class="num" name="total" value="0.00" readonly="readonly" />
</label>
</p>
</fieldset>
</form>