I have to build a form and I have been working on the jQuery, but I get stuck in one step if you can give me any advice please,
So let me explain a bit about the form I have 20 products with offer1, offer2, and monthly fee all this till now is working perfectly i just need after you choose the amount of the specific product and when you press on the next button to display again the result but only where the amount was filled so basically only the products what the customer is interesting about them, and here is my main problem I know I have to do in jQuery each function but I am not sure how to do it ?
I have attached a picture to with the form so you can see an example
form picture
Edit:
Here is my code at the moment:
function convert(value) {
return "" + ((Number(value) || 0).toFixed(2).replace(/(\d)(?=(\d{3})+
(?!\d))/g, "$1,")) + "";
}
function testing(id, normaloffer, talesalesoffer, montlyoffer) {
var normaoffertotal = normaloffer * $('#amount' + id).val();
var talesalestotal = talesalesoffer * $('#amount' + id).val();
var montlytotal = montlyoffer * $('#amount' + id).val();
$(".normaloffertotal" + id).html(normaoffertotal);
$(".telesalesoffertotal" + id).html(talesalestotal);
$(".montlytotal" + id).html(montlytotal);
$('#hnoffer' + id).val(normaoffertotal);
}
console.log(convert(10496.470000000001));
function normaloffertotalcalc() {
var sumnormaltotal = 0;
$('span[id^="normaloffertotalspan"]').each(function () {
var text = $(this).text();
sumnormaltotal += parseFloat(text, 10);
});
$('#sumnormaltotal').html(sumnormaltotal);
var sum_telesale = 0;
$('span[id^="telesalesoffertotalspan"]').each(function () {
var text = $(this).text();
sum_telesale += parseFloat(text, 10);
});
$('#sumtelesaletotal').html(sum_telesale);
var sum_montly = 0;
$('span[id^="montlyofferspan"]').each(function () {
var text = $(this).text();
sum_montly += parseFloat(text, 10);
});
$('#summontlytotal').html(sum_montly);
console.log('Normal Total Offer ' + convert(sum_normal));
console.log('TeleSales Total Offer ' + convert(sum_telesale));
console.log('Montly Total Offer ' + convert(sum_montly));
}
</script>
and here is the html
<?php
$count = 0;
$query = mysqli_query($con, "SELECT * FROM products");
while ($row = mysqli_fetch_array($query)) {
$count++;
?>
<tr>
<td align="center"><?= $row[1] ?></td>
<td align="center"><input type="text" placeholder="0" id="amount<?= $count ?>"
name="amount<?= $count ?>" onblur="normaloffertotalcalc()"
onkeyup="testing(<?= $count ?>, <?= $row[2] ?>, <?= $row[3] ?>, <?= $row[4] ?>)"
style="-webkit-appearance: none; background: none; text-align: center; border: none; width: 40px;">
</td>
<td align="center">£<?= $row[2] ?></td>
<td align="center">£<span class="normaloffertotal<?= $count ?>"
id="normaloffertotalspan">0</span> <input type="hidden"
class="normaloffertotalspan"
id="hnoffer<?= $count ?>">
</td>
<td align="center">£<?= $row[3] ?></td>
<td align="center">£<span class="telesalesoffertotal<?= $count ?>" id="telesalesoffertotalspan">0</span>
</td>
<td align="center">£<?= $row[4] ?></td>
<td align="center">£<span class="montlytotal<?= $count ?>" id="montlyofferspan">0</span></td>
</tr>
<?php } ?>
I find a solution for me with this problem
$('input[type=text]').each(function(){
var val = parseInt($(this).val());
if(val > 0){
var id = $(this).attr('id');
if(id){
console.log(id);
}
console.log(val);
}
});
this is the code what I did and is working perfectly :)
Thanks to everyone who gives me advice
Ups one more thing, do you have any idea how can I export from MySQL only the products who have the id 2,7,1 example :)
Related
As stated in the title my code works in local but not on server.
More precisely, when i call whatever PHP function it doesn't find my JS function.
To sum it up : The goal here is to generate an excel (.XLS) file from an HTML table which is created by retrieving data from a database. Everything works flawlessly in local with my Wamp server but when I move it to server I get this error when calling the JS function getDashboardResumeJ ():
DashboardResume.php:124 Uncaught ReferenceError: getDashboardResumeJ is not defined
If I remove all the PHP in the main file everything works when on server.
PHP in main file :
<button id="buttonXLS" href="#" onclick="exportTableToExcel('tableRecap', 'Rapport Mensuel <?php echo $year . '/' . $month?>')">Export to Excel</button>
<table style="display:none" id="tableRecap" >
<tr>
<td style="font-weight: bold">Nom et prénom</td>
<?php $arrayId = array(selectTableEmploye('nom', 'prenom')); ?>
</tr>
<tr>
<td style="font-weight: bold">Date d'entrée</td>
<?php selectTableEmploye('date_embauche'); ?>
</tr>
<tr>
<td style="font-weight: bold">Date de sortie</td>
<?php selectTableEmploye('date_depart'); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 1</td>
<?php selectTableTimesheet('commentaire1',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 2</td>
<?php selectTableTimesheet('commentaire2',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 3</td>
<?php selectTableTimesheet('commentaire3',$arrayId,$month,$year); ?>
</tr>
<tr>
<td style="font-weight: bold">Remarque 4</td>
<?php selectTableTimesheet('commentaire4',$arrayId,$month,$year); ?>
</tr>
<?php
generateDays($dateMonth, $dateYear);
?>
</table>
JS in main file :
<script>
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
$(document).ready(function(){
$('.month_dropdown').on('change',function(){
getDashboardResumeJ('dashboard_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
$('.year_dropdown').on('change',function(){
getDashboardResumeJ('dashboard_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
getCommJ();
});
function getDashboardResumeJ(target_div, year, month){
$.ajax({
type:'POST',
url:'functionsDashboardResume.php',
data:'func=getDashboardResumeP&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
}
});
}
PHP functions called by main file PHP :
<?php
function selectTableEmploye($attribute, $optAttribute = '')
{
include "dbConfig.php";
$query = 'SELECT * FROM employe ORDER BY id_employe ASC';
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
$arrayId = [];
if ($optAttribute != '') {
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . ' ';
echo $row[$optAttribute] . '</td>';
array_push($arrayId, $row['id_employe']);
}
} else {
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
/* free results */
$stmt->free_result();
}
return $arrayId;
}
function selectTableTimesheet($attribute, $arrayId, $month, $year)
{
include "dbConfig.php";
if (!empty($arrayId)) {
foreach ($arrayId[0] as $value) {
$query =
'SELECT DISTINCT commentaire1,commentaire2,commentaire3,commentaire4 FROM timesheet,employe WHERE timesheet.id_employe =' .
$value. ' AND timesheet.annee = ' . $year . ' AND timesheet.mois = ' . $month;
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
}
}
else{
$query =
'SELECT * FROM timesheet';
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<td> ' . $row[$attribute] . '</td>';
}
}
}}
function generateDays($month, $year)
{
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
for ($i = 1; $i <= $daysInMonth; $i++) {
if($month != 10){
$monthFunc = trim($month,0);
}
else{
$monthFunc = 10;
}
$data = getActivity($i,$monthFunc,$year);
$flag_half_day = 0;
$flag_row_number = 1;
$secondRowContent = array();
$numItems = mysqli_num_rows($data);
$checkIndex = 0;
echo "<tr>" . "<td style='text-align: right;font-weight: bold;'>" . $i . "</td>" ;
while ($row = $data->fetch_assoc()) {
if($flag_row_number == 1){
//cas 2b
if ($flag_half_day == 1){
array_push($secondRowContent,'<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>');
$flag_half_day = 0;
}
else{
//cas 1
if($row['nombre_heure'] == 8){
echo '<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>';
array_push($secondRowContent,'<td></td>');
$flag_half_day = 0;
}
//cas 2a
else if(is_null($row['nombre_heure'])){
echo '<td></td>';
}
else{
echo '<td>' . $row['code_fiduciaire'] . $row['nombre_heure'] . '</td>';
$flag_half_day = 1;
}
}
if($checkIndex++ == ($numItems - 1)){
$flag_row_number = 2;
echo "</tr>";
}
}
}
if($flag_row_number == 2){
echo '<tr> <td style="text-align: right;font-weight: bold;">' . $i . '</td>';
foreach($secondRowContent as $content){
echo $content;
}
echo '</tr>';
}
else{
echo '<tr> <td style="text-align: right;font-weight: bold;">' . $i . '</td> </tr>';
}
}
}
function getActivity($day, $month, $year){
include "dbConfig.php";
$query =
'select time_dimension.db_date, time_dimension.holiday_flag, employe.id_employe, employe.nom, timesheet.nombre_heure, timesheet.date, taches.code_fiduciaire FROM time_dimension left outer join employe on time_dimension.db_date >= employe.date_embauche left outer join timesheet on timesheet.date = time_dimension.db_date AND timesheet.id_employe = employe.id_employe left outer join taches on timesheet.id_tache = taches.id_tache where time_dimension.year = ' . $year . ' and time_dimension.month = ' . $month . ' and time_dimension.day = ' . $day . ' AND COALESCE (timesheet.nombre_heure,1) != 0 ORDER BY employe.id_employe, time_dimension.db_date' ;
if ($stmt = $db->prepare($query)) {
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
return $result;
}
}
?>
If you need more snippets or informations don't hesitate.
Thanks for your help,
Have a great day
For those who have the same kind of problem, the server I was working on didn't have the same PHP version as the one I was working in local.
Try phpinfo() both in local and on your server to check your PHP version is the same.
need help i am working with some text inputs here that are dynamic depending on how many the user enter. what i wanted to do is to compute the text inputs automatically after user input value using onkeyup javascript.
here the php and html code:
<?Php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply()' id='tb1'>";
echo "x";
echo "<input type='text' onkeyup='multiply()' id='tb2'>";
echo "=";
echo "<input type='text' onkeyup='multiply()' id='tb3'>";
echo "<br>";
}
?>
total:<input type='text' onkeyup='multiply()' id='tb4'>
and here's the javascript:
<script>
function multiply(){
var textbox1 = document.getElementById('tb1').value;
var textbox2 = document.getElementById('tb2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb3').value = result;
}
}
</script>
now, the first row of text inputs works fine but the remaining text inputs doesn't I know i'm missing something here and i can't figure it out, how can
i compute horizontally those values from tb1 and tb2 then display it on tb3
and compute vertically all the values of tb3 and display it in tb4. any help is much appreciated.TIA
Well all rows contain elements with same ids. So row 1 will contain elements with ids: tb1, tb2, tb3. Row 2 will also contain elements with ids tb1, tb2 and tb3.
The id of each element on a page needs to be unique. You can make the ids unique by appending the row number to the id. For example:
<?php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-1'>";
echo "x";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-2'>";
echo "=";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-3'>";
echo "<br>";
}
?>
Total: <input type='text' id='tb4'> <input type='button' onclick='CalculateSum()' title='Calculate Sum'>
Your JavaScript code will then look as follows:
<script>
function multiply(row) {
var textbox1 = document.getElementById('tb' + row + '-1').value;
var textbox2 = document.getElementById('tb' + row + '-2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb' + row + '-3').value = result;
}
}
function CalculateSum() {
let total = 0;
for (let i=0; i < 10; i++) {
total += document.getElementById('tb' + i + '-3').value;
}
document.getElementById('tb4').value = total;
}
</script>
i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});
I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);
I have problem with this script. When I change value in column "TO" in table, script substract automatically in column "Number of hours" only in first row value but others no. I need application script with name "PRO1" (updateDue) in every row in table.
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<body onload="changeText()">
<?php
$date = date('Y-m-01');
$end = date('Y-m-t');
//, strtotime('-1 months')//
?>
<?php include 'dbconfig.php' ?>
<table border="1" id="myTable">
<tr>
<td>Date</td>
<td>From</td>
<td>To</td>
<td>Number of hours</td>
</tr>
<tr class="item">
<?php
date_default_timezone_set('UTC');
while(strtotime($date) <= strtotime($end)) {
$day_num = date('d', strtotime($date));
$day_name= date('l', strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
if (($day_name == "Saturday")||($day_name == "Sunday"))
{
echo "<td id='color'>$day_num $day_name</td><td></td><td></td><td></td></tr>";
}
else {
echo "<td>$day_num $day_name</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$starter= $query_row['start'];
echo "<input type='text' class='txtCal' id='num1' onchange='updateDue()' value=".$query_row['start'].">";
}
echo "</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$finisher= $query_row['end'];
echo "<input type='text' class='txtCal' id='num2' onchange='updateDue()' value=".$query_row['end'].">";
}
echo "</td><td>";
$ts1 = strtotime($starter);
$ts2 = strtotime($finisher);
$seconds_diff = $ts2 - $ts1;
$time = ($seconds_diff/3600);
echo "<input type='text' class='txtCal2' id='remainingval' value=".number_format((float)$time, 2, '.', '').">";
echo "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td></td>
<td>Sum:</td>
<td id="total_sum_value"><span id="total_sum_value"></span></td>
</tr>
</table>
<br>
<!-- SCRIPT NAME PRO1 -->
<script>
function updateDue() {
$('#myTable tr').each(function(){
var total = parseFloat(document.getElementById("num2").value);
var val2 = parseFloat(document.getElementById("num1").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
});
}
</script>
<script>
$(document).ready(function changeText(){
$(document).ready(function changeText(){
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
calculated_total_sum += parseFloat(get_textbox_value);
});
$("#total_sum_value").html(calculated_total_sum);
});
$("#myTable").on('change','input', '.txtCal2', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
</script>
I want dynamically change table. In column "FROM" and "TO" is value from database. This automatically subtract value (TO-FROM) and sum from this value is down. But when user change some value in column "FROM" or "TO", number will be count automatically. Thank you so much for every advice.
That's because you use the same ID for multiples TDs. You can't do that as an ID is supposed to be used once and help to identify a resource.
instead of an ID, you could use a class :
<table>
...
<tr>
<td><input type="text" class="txtCal num1" value="5" /></td>
<td><input type="text" class="txtCal num2" value="10" /></td>
<td><input type="text" class="txtCal2 remainingval" value="...">
</tr>
...
</table>
Then with jQuery, you can have access to your row values like this :
$('#myTable tr').each(function(){
var total = parseFloat($(this).find('.num2').val());
var val2 = parseFloat($(this).find('.num1').val());
...
var ansD = $(this).find(".remainingval");
ansD.val(total - val2);
});
Also let me point that mysql functions are deprecated and you should not use them anymore. Use PDO instead. (See Why shouldn't I use mysql_* functions in PHP?)