Repeating jquery script in every row in table automatically - javascript

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?)

Related

all data is in page 1 after calling tbody via AJAX

May I ask for assistance regarding this matter? I checked every guide regarding this concern, and followed all guide, but no luck.
When the table is populated via AJAX call, all the data is in a single page only.
I tried adding the whole dataTable script into the tbody caller, but no luck.
These are the following codes.
This is my <?php include 'ajax-process/earnings_amendment_account-ajax-table.php'; ?>
<script>
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url:'table_body/earnings_amendment_account_table_body.php',
dataType:'json',
type:'get',
cache:true,
success:json,
});
function json(data){
$("#earnings_amendment_account_body").empty();
$(data).each(function(index,value) {
console.log(value);
var table = '<tr>' +
'<td>' + value.accountcode + '</td>'+
'<td>' + value.accounttitle + '</td>'+
'<td>' + value.accounttype + '</td>'+
'</tr>';
$('#earnings_amendment_account').append( table );});
}
}, 1000);
$('#earnings_amendment_account').dataTable();
});
</script>
This is my table in index.php
<table id="earnings_amendment_account" class="table table-bordered" style="table-layout: fixed; display: none">
<thead>
<th>Account Code</th>
<th>Account Title</th>
<th>Account Type</th>
</thead>
<tbody id="earnings_amendment_account_body">
</tbody>
</table>
This is my table_body/earnings_amendment_account_table_body.php
<?php
include '../backend/conn.php';
include '../backend/session.php';
$params=array();
$sql = "SELECT accountcode,accounttype,accounttitle,accounttype,postedby,dateposted,
approvedby,dateapproved FROM earningsamendmentaccount";
$query = sqlsrv_query($conn, $sql, $params, array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($query === false ) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; }
$dbdata = array();
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$dbdata[]=$row;
}
echo json_encode($dbdata);
?>
This is my dataTable.
// all of the function in this dataTable is still not included because I'm testing if everything works well when my dataTable body is being called via AJAX.
<script>
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({
"pagingType": "full_numbers"
});
$('#earnings_amendment_account').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = earnings_amendment_account_table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Posted By : ' : tr.data('key-1'),
'Date Posted : ' : tr.data('key-2'),
'Approved By : ' : tr.data('key-3'),
'Date Approved : ' : tr.data('key-4')
})).show();
tr.addClass('shown');
} });
</script>
The data is being passed on console. Showing 0 out of 0 Entries, but the data is on display in the page.
Top:
Bottom:
Thank you so much in advance.
here is i did basic example of datatabe, you need to follow this things if you are using datatable and do custom thing.
Index.php
<!DOCTYPE html>
<html leng="en">
<head>
<title>Display Emloyee </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="table-responsive">
<table class="table table-striped" id="tabl_user">
<thead>
<tr>
<th>Id</th>
<th>F Name</th>
<th>L Name</th>
<th>Gender</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function()
{
$('#tabl_user').DataTable( {
"processing": true,
"serverSide": true,
"lengthMenu": [5, 10, 25, 50, 100, 150],
"columnDefs" : [{orderable:false, targets:[1] }],
"ajax": "trylimited.php"
} );
});
</script>
</div>
</div>
</body>
</html>
trylimited.php
<?php
include "con.php";
$column = array('id', 'first_name', 'last_name', 'phone_no', 'mobile','city', 'zip');
$sIndexColumn = "id";
$sTable = "elision_user";
// Searching
$wherecondition = "";
if($_REQUEST['search']['value'] != "")
{
$wherecondition = "WHERE (";
for($i=0; $i<count($column); $i++)
{
$wherecondition .="".$column[$i]." LIKE '%".$_REQUEST['search']['value']."%' OR ";
}
$wherecondition = substr_replace($wherecondition, "", -3);
$wherecondition .=')';
}
$draw = $_REQUEST['draw'];
$start = $_REQUEST['start'];
$limit = $_REQUEST['length'];
$sql = "SELECT * FROM allinone";
$res = mysqli_query($con, $sql);
$sql1 = "SELECT * FROM elision_user";
$sql1.=" $wherecondition ORDER BY ".$column[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir']." limit $start, $limit";
$res1 = mysqli_query($con, $sql1);
$recordsTotal = mysqli_num_rows($res1);
$recordsFiltered = mysqli_num_rows($res);
$asd = array();
$final_array = array();
while( $row = mysqli_fetch_array($res1) ) {
$dataArray = array();
$dataArray[] = $row["id"];
$dataArray[] = $row["first_name"];
$dataArray[] = $row["last_name"];
$dataArray[] = $row["phone_no"];
$dataArray[] = $row["mobile"];
$dataArray[] = $row["city"];
$dataArray[] = $row["zip"];
$asd[]=$dataArray;
}
$final_array = array("draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $asd, "sql" => $sql1);
echo json_encode($final_array); exit;
?>
Hope this example will help you for your concern.
please vote positive if this example will helpfull

jQuery each function result how to do?

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 :)

POST Ajax request

I'm working on an old project that wasn't developed by me at first. I need to make an Ajax request so that the values contained in the fields (more on that later) be sent to a php script which will then return their values into the correct td.
Here is the JavaScript/jQuery code.
$(function ()
{
$('form').on('submit', function (e)
{
e.preventDefault();
$.ajax
({
type: 'post',
url: 'envoi_dispo_semaine.php',
data: $('form').serialize(),
success: function ()
{
alert('Le planning a été mis à jour.');
}
});
});
jQuery(document).ready(function date()
{
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
var today = new Date();
var t = today.getWeek();
})
jQuery(document).ready(function()
{
jDispo = {};
jCharge = {};
jSolde = {};
var d = 0;
var c = 0;
var s = 0;
jQuery('.DISPO').each(function()
{
jDispo[d] = jQuery(this).val();
d++;
});
jQuery(".CHARGE").change(function()
{
var totalCharge = 0;
if(jQuery(".CHARGE").length > 0)
{
jQuery(".CHARGE").each(function()
{
jCharge[c] = jQuery(this).val();
c++;
totalCharge = totalCharge + jQuery(this).val();
});
}
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function()
{
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
});
});
$(document).ready(function()
{
if ($("#tab_projets table tbody tr:eq(2) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(5) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(8) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('font-color', 'black');
}
});
});
And here is check_charges.php:
<?php
include('connexion_db.php');
$charge = $_POST['charge'];
$dispo = $_POST['dispo'];
$solde = $_POST['solde']; //I'll need this one later on.
$res = $dispo - $charge;
echo $res;
?>
I also have some php code that allows me to generate a table (it's in the same file as the javascript):
<thead>
<?php
echo " <td colspan=2>Semaine n°</td>
<td>Retard</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
echo "<form action=\"envoi_dispo_semaine.php\" method=\"post\">
<td>
<input type=\"hidden\" name=\"semaine_id\" value=\"".$i."\" />".$i."</td>";
}
?>
</thead>
<tbody>
<?php
foreach($users as &$myUser)
{
echo " <tr class=".$myUser.">
<td width=66% rowspan=3><input type=\"hidden\" name=\"login\" value=\"".$myUser."\" onblur=\"updateCharge\"/>".$myUser."</td>
<td width=34%>Disponibilité</td>
<td rowspan=3></td>
";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query = requete_is_plancharges($req);
$row = mysql_fetch_row($query);
$affichageDispo = $row[0];
if ($affichageDispo == "")
{
$affichageDispo = 3;
}
echo "
<td>
<input class=\"DISPO\" type=\"number\" name=\"disponibilite[]\" value=".$affichageDispo." min=\"0\" max=\"5\" step=\"0.5\" class=\"input\"/>
</td>
";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Charge</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$reqTache = "
SELECT tache_id
FROM Tache
WHERE ebi_id = ".$ebi."
AND demande_id = ".$demande."
AND action_id = ".$action;
$resultatTache_id = requete_is_plancharges($reqTache);
$maTache = mysql_fetch_object($resultatTache_id);
$req_Charge = "
SELECT COUNT(charge) as charge_tache
FROM Charge_par_tache
WHERE tache_id =".$maTache->tache_id.
" AND semaine_id =".$i.
" AND login = '".$myUser."'";
$resultat_requete_Charge = mysql_fetch_object(requete_is_plancharges($req_Charge));
if ($resultat_requete_Charge->charge_tache > 0)
{
$req = "
SELECT Charge_par_tache.charge
FROM Charge_par_tache, Tache
WHERE Charge_par_tache.tache_id = Tache.tache_id
AND Tache.ebi_id = ".$ebi."
AND Tache.demande_id = ".$demande."
AND Tache.action_id = ".$action."
AND Charge_par_tache.login = '".$myUser."'
AND Charge_par_tache.semaine_id = ".$i;
$Charge = mysql_fetch_object(requete_is_plancharges($req));
} else
{
$Charge->charge = "";
}
echo " <input type = \"hidden\" name = \"tache_id\" value=".$maTache->tache_id.">
<td class=\"CHARGE\">";
$query = requete_is_plancharges($req);
$row = mysql_fetch_array($query);
$affichageCharge = $row[0];
echo " <input class=\"CHARGE\" type=\"number\" name=\"charge[]\" value=".$Charge->charge." min=\"0\" step=\"0.5\"/>
</td>";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Solde</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req1 = "
SELECT charge FROM Charge_par_tache WHERE login = '".$myUser."' AND semaine_id = ".$i;
$req2 = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query1 = requete_is_plancharges($req1);
$row1 = mysql_fetch_row($query1);
$query2 = requete_is_plancharges($req2);
$row2 = mysql_fetch_row($query2);
$solde=$row2[0]-$row1[0];
echo "<td class=\"SOLDE\"><input type=\"hidden\" class=\"SOLDE\" value=".$solde."/> ".$solde."</td>";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
<p><input type="submit" name="submit" value="Mise à jour"></p>
</form>
The problem is that I can't seem to retrieve $res. I'm just starting Ajax so I really don't know what to do, and couldn't find the answer on the Internet as I use a js array to store my values.
If I understand your problem you want to get the response value of "check_charges.php", that it is the $res value, isn't it? The value will be returned in the first parameter of success function of your ajax.
Your code:
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function(data)
{
// Store where you want the data value
alert('res value: ' + data);
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
I hope I have helped you.

Cloned elements' events corresponding to all elements in the form

I successfully cloned my table rows, which has values retrieved from database. However I have few issues with it.I used class for all the elements as clone will duplicate IDs.No the problem raises because it unable to target each element uniquely. WHat's the way to do make each element / row unique here?
How the functions work:
When first select box selected, item for that selected id would appear in the next column.Followed by price textbox and quantity textbox. WHen both are filled up, last textbox for total amount would automatically appear.
Issues with the cloning are:
* WHen select box selected from the first/original row, all cloned items are updated with the value.Same goes for amount textbox and vise-versa.
My script:
<script>
var harga;
var qty;
$("input[name^=harga]").on("keyup", function () {
alert($(this).attr("id"));
console.log($(this).val());
harga = $(this).val();
});
$(".qty").on("keyup", function () {
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$(".amount").val(amount);
});
$(document).ready(function () {
$(".sub_item").hide();
$('.gr').change(function () {
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['
agency_id
'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".sub_item").show();
$(".it_id").empty();
for (i = 0; i < data.length; i++) {
$(".it_id").append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$(".it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$("#more_items").on("click", function () {
alert("Hi");
$(".clone_this").clone(true, true).insertBefore("#last_e");
});
$(function () {
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function () {
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide1").show();
} else {
$("#hide1").hide();
}
});
$('#insurance').change(function () {
$("#hide2").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide2").show();
} else {
$("#hide2").hide();
}
});
$('#bon').change(function () {
$("#hide3").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide3").show();
} else {
$("#hide3").hide();
}
});
});
</script>
Form
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr>
<th>Group Item</th>
<th>Nama Item</th>
<th>Harga</th>
<th>Kuantiti</th>
<th>Amount</th>
</tr>
<tr class="clone_this">
<td>
<select name='group' style="width:80px;" class="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach ($group as $k => $v) {
$i = 0;
$i++;
?>
<option value="<?php echo $v['group_id'] ?>"><?php echo $v['group_name'] ?></option>
<?php
}
?>
</select>
</td>
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
</select>
</td>
<td><input type="text" name="harga_<?php echo $i; ?>[]" id="<?php echo $i; ?>" value="" class="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty[]' class='qty'/>
</td>
<td><input type="text" name="amount[]" class="amount" value=""/></td>
</tr>
<tr id="last_e">
<td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
You need find the relative elements to update so
$(document).ready(function () {
$('#submit_item').on('keyup', '.qty, .harga', function () {
var $tr= $(this).closest('tr');
$tr.find('.amount').val($tr.find('.harga').val() * $tr.find('.qty').val() || 0)
})
$(".sub_item").hide();
$('#submit_item').on('change', '.gr', function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});
Demo: Fiddle

insert dropdown field from mysql using jquery

hi i have a page of invoice where i can add rows using jquery. i am able to add plain text box from .js file but i want to add a drop down menu insted of textbox. justlike default row in php page.
my page code is
<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("inventory_erp",$con);
$getitem=mysql_query("SELECT * FROM 0_stock_master ORDER BY stock_id ASC");
$item = '';
while($row = mysql_fetch_assoc($getitem))
{
$item .= '<option value = "'.$row['id'].'">'.$row['stock_id'].'</option>';
}
$getdescription=mysql_query("SELECT * FROM 0_stock_master ");
$description = '';
while($row2 = mysql_fetch_assoc($getdescription))
{
$description .= '<option value = "'.$row2['description'].'">'.$row2['description'].'</option>';
}
?>
<!DOCTYPE html>
<!-- saved from url=(0047)http://css-tricks.com/examples/EditableInvoice/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Editable Invoice</title>
<script src="./Editable Invoice_files/jquery-1.3.2.min.js"></script>
<script src="./Editable Invoice_files/example.js"></script>
</head>
</html>
<table id="items">
<tbody><tr>
<th>Item</th>
<th>Description</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $item; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><select name="age"> <?php echo $description; ?> </select></td>
<td><textarea class="cost">$0.00</textarea></td>
<td><textarea class="qty">1</textarea></td>
<td><span class="price">$0.00</span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value"><div id="total">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid">$0.00</textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due">$0.00</div></td>
</tr>
</tbody></table>
i am using a example.js file to add rows dynamically.
example.js
function print_today() {
// ***********************************************
// AUTHOR: WWW.CGISCRIPT.NET, LLC
// URL: http://www.cgiscript.net
// Use the script, just leave this message intact.
// Download your FREE CGI/Perl Scripts today!
// ( http://www.cgiscript.net/scripts.htm )
// ***********************************************
var now = new Date();
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
var today = months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
return today;
}
// from http://www.mediacollege.com/internet/javascript/number/round.html
function roundNumber(number,decimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
numString += ".";// give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff,cutoff+1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0,cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
for(var i=0;i<decimals-decs;i++) newString += "0";
//var newNumber = Number(newString);// make it a number if you like
return newString; // Output the result to the form field (change for your purposes)
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("$"+total);
$('#total').html("$"+total);
update_balance();
}
function update_balance() {
var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
due = roundNumber(due,2);
$('.due').html("$"+due);
}
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
update_total();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
$(document).ready(function() {
$('input').click(function(){
$(this).select();
});
$("#paid").blur(update_balance);
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $option; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea>Description</textarea></td><td><textarea class="cost">$0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
update_total();
if ($(".delete").length < 2) $(".delete").hide();
});
$("#cancel-logo").click(function(){
$("#logo").removeClass('edit');
});
$("#delete-logo").click(function(){
$("#logo").remove();
});
$("#change-logo").click(function(){
$("#logo").addClass('edit');
$("#imageloc").val($("#image").attr('src'));
$("#image").select();
});
$("#save-logo").click(function(){
$("#image").attr('src',$("#imageloc").val());
$("#logo").removeClass('edit');
});
$("#date").val(print_today());
});
i am using this code in exampe.js file to add text box (Description) in new row. but i want a drop down menu from mysql database.

Categories

Resources