I have these HTML code that fetch data from database. I set an array to HTML input.
Html code
<table>
<thead>
<tr>
<th>Category</th>
<th>January</th>
<th>February</th>
</tr>
</thead>
<tbody>
<?php
$sql = DB::getInstance()->FetchArray("select * from table");
if(count($sql) > 0)
{
foreach($sql as $row)
{
$i = 0;
if($i == 0)
{?>
<tr>
<td><input type="text" class="cat1" id="cat1" name="cat1[]" value="<?php echo $row['CATEGORY']; ?>" placeholder="" readonly></td>
<td><input type="text" class="jan1" id="jan1" name="jan1[]" value="<?php echo (($row['MONTH']=='JANUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
<td><input type="text" class="feb1" id="feb1" name="feb1[]" value="<?php echo (($row['MONTH']=='FEBRUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
</tr>
<?php
}
else
{?>
<tr>
<td></td>
<td><input type="text" class="jan1" id="jan1" name="jan1[]" value="<?php echo (($row['MONTH']=='JANUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
<td><input type="text" class="feb1" id="feb1" name="feb1[]" value="<?php echo (($row['MONTH']=='FEBRUARY')? $row['TOTAL']:''); ?>" placeholder="" readonly></td>
</tr>
<?php
}
$i++;
}
?>
<tr>
<td colspan="2" style="text-align:right;">Total</td>
<td><input type="text" class="form-control inputnumberwith2decimals total_jan1" id="total_jan1" name="" value="" placeholder="" readonly></td>
<td><input type="text" class="form-control inputnumberwith2decimals total_feb1" id="total_feb1" name="" value="" placeholder="" readonly></td>
</tr>
</tbody>
</table>
The value for jan1[] display in console.log as
NaN
1000
3000
NaN
When i try to sum the total for jan1[], the output show as NaN because some of the array value is NaN. How can I set NaN value to 0 and do the sum calculation ?
What I want to achieve is to sum up the value like below
CATEGORY JANUARY FEBRUARY
BANANA NaN NaN
1000 NaN
2000 NaN
NaN NaN
TOTAL 3000 0
Here's the code for jQuery.
<script>
$(document).ready(function(){
var sum_jan1 = parseFloat(0);
$(".jan1").each(function(){
var value = parseFloat($(this).val());
sum_jan1 += value;
});
$('#total_jan1').val(sum_jan1);
});
</script>
Thanks.
You just need to convert the NaN values to 0 in your sum function. Following is an example using reduce:
const arr = [NaN, 1000, 3000, NaN];
const sum = arr.reduce((acc, num) => acc += num || 0, 0);
console.log(sum);
// 4000
Try this
<script>
$(document).ready(function(){
var sum_jan1 = parseFloat(0);
$(".jan1").each(function(){
var value = parseFloat($(this).val());
sum_jan1 += value?value:0;
});
$('#total_jan1').val(sum_jan1);
});
just replace var value = parseFloat($(this).val());
to
var value = $(this).val() ? $(this).val() : 0; line.
This will solve your issue.
Related
please help me..,
I create a loop for the database input with one input affecting the other input,
when run, the first line will be successful (the input changes) but it does not happen on line two and the others ,,, this is my script..
#foreach($products as $product)
<tr>
<td>
{{$product->product}}</td>
<td class="text-center"><?php
if ($product->enable_stock) {
$stock = $product->stock ? $product->stock : 0 ;
$fstock = (float)$stock . ' ' . $product->unit;
} else {
$fstock = 'N/A';
}
?>
<input type="text" class="form-control" name="stock" id="stock" style='width:100%; text-align:center' value= " {{$product->stock}} ">
</td>
<td>
<input onchange="diff(this.value)" type="text" class="form-control" name="hso" id="hso" style='width:100%; text-align:center' value= " {{$product->stock}} "></td>
<td>
<input type="text" class="form-control" name="diff" id="diff" style='text-align:center' value="">
</td>
</tr>
<script type="text/javascript">
function diff() {
var stock = document.getElementById("stock").value;
var hso = document.getElementById("hso").value;
var diff = eval(hso) - eval(stock);
document.getElementById("diff").value=diff;
}
</script>
#endforeach
<?php $i=0;?>
#foreach($products as $product)
<?php $i++;?>
<tr>
<td>
{{$product->product}}</td>
<td class="text-center"><?php
if ($product->enable_stock) {
$stock = $product->stock ? $product->stock : 0 ;
$fstock = (float)$stock . ' ' . $product->unit;
} else {
$fstock = 'N/A';
}
?>
<input type="text" class="form-control" name="stock" id="stock{{$i}}" style='width:100%; text-align:center' value= " {{$product->stock}} ">
</td>
<td>
<input onchange="diff(this.value)" type="text" class="form-control" name="hso" id="hso{{$i}}" style='width:100%; text-align:center' value= " {{$product->stock}} "></td>
<td>
<input type="text" class="form-control" name="diff" id="diff{{$i}}" style='text-align:center' value="">
</td>
</tr>
<script type="text/javascript">
$(document).ready(function () {
function diff() {
var stock = document.getElementById("stock{{$i}}").value;
var hso = document.getElementById("hso{{$i}}").value;
var diff = eval(hso) - eval(stock);
document.getElementById("diff{{$i}}").value=diff;
}
});
</script>
#endforeach
This is my page and i have to calculate the 4th row of the table.This table is that i am fetching from the table withing particular date.
The fourth row is empty that i have to feed and update into the table.
I doing calculation in that table should add the rows and show in below.
But it shows NAN.
My Code:
<script>
$(document).ready(function(){
$('.ramt').on('change input',function() {
var tot = 0;
var sub = 0;
$('#tb3 > tbody > tr').each(function() {
var pamt = $(this).find('.ramt').val();
tot += parseFloat(pamt);
});
$('#rtotal').val(tot);
});
});
</script>
this is my table code :
<?php
//echo '<pre>';print_r($result2);exit();
if(!empty($query)){
foreach($query as $key => $row){ // added $key as index
?>
<tr >
<td ><input style="width:50px" type="text" class="form-control input-xs Sno" name="Sno[<?php echo $key ?>]" id="Sno" value="<?=$row['loan_no'];?>"></td>
<td> <input style="width:180px" type="text" class="form-control input-xs" name="name[<?php echo $key ?>]" id="Amount" value="<?=$row['pname'];?>"></td>
<td ><input style="width:50px" type="text" class="form-control input-xs amt" name="Amount[<?php echo $key ?>]" id="Bankname" value="<?=$row['collection_amt'];?>"></td>
<?php $total_sum=0; ?>
<?php if($row['receive_amt'] != 0)
$total_sum = $row['receive_amt'];
else{
$total_sum = "";
} ; ?>
<td ><input style="width:50px" type="text" class="form-control input-xs ramt" name="ramt[<?php echo $key ?>]" id="Chqamt" value="<?php echo"$total_sum"?>" autofocus></td>
</tr>
<?php
}
}?>
</tbody>
Can you not just iterate over the ramt inputs directly?
<script>
$(document).ready(function(){
$('.ramt').on('change input',function() {
var tot = 0;
$('.ramt').each(function() {
let val = $(this).val();
if(val !== '') {
tot += parseInt(val);
}
});
$('#rtotal').val(tot);
});
});
</script>
I have an issues for searching and displaying data to table with javascript. i have data with format json but all it can't displayed on table just 1st row, while on console log.data five rows displayed. how to solved this problem. thanks you so much for you guys i hope here this solved.
This is the data:
var data =[
{header_id:"TR100001" detail_id:"2" item_code:"SPH001" price:"4000" weight:"2"},
{header_id:"TR100001" detail_id:"3" item_code:"SPH002" price:"4500" weight:"2"},
{header_id:"TR100001" detail_id:"4" item_code:"SPH003" price:"30000"weight:"2"},
{header_id:"TR100001" detail_id:"5" item_code:"SPH004" price:"45000"weight:"2"}];
This's View:
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="buy_transaction" class="table table-bordered table-hover table-striped sticky-header">
<thead class="bg-success">
<tr>
<th width="1">☑</th>
<th width="5"><b>Detail</b></th>
<th><b>Item Code</b></th>
<th><b>Price</b></th>
<th><b>Weight</b></th>
</tr>
</thead>
<tbody id="dataTable2">
<table id="buy_transaction">
<tbody id="dataTable2">
<td><input type="checkbox" class="chk" name="chk[]" value="<?php echo $detail->detail_id; ?>"></td>
<td><input type="text" id="detail_id" name="detail_id[]" class="detail_id form-control" value="<?php echo $detail->detail_id ;?>" size="1"> </td>
<td><input type="text" width="10" class="item_code form-control" id="item_code" name="item_code[]" value="<?php echo $detail->item_code; ?>"></td>
<td><input type="text" class="header_id1 form-control" id="header_id" name="header_id[]" value="<?php echo $detail->header_id; ?>" readonly ></td>
<td><input type="text" class="price form-control" id="price" name="price[]" value="<?php echo $detail->price; ?>" readonly ></td>
<td><input type="text" class="weight form-control" id="weight" name="weight[]" placeholder="0" value="<?php echo $detail->weight; ?>"></td>
</table>
</div>
</div>
</div>
This's Javascript Code :
<script type="text/javascript">
function getdHeaderid(header_id){
var header_id = header_id.val();
$.ajax({
type : "post",
data : {header_id:header_id},
url : "<?php echo base_url();?>index.php/transaction/selltransaction/get_dtHeaderid",
dataType:"json",
cache :false,
success: function(data){
console.log(data);
for(var i=0; i< data.length; i++){
var obj=data[i];
$(".header_id").val(obj.header_id);
$(".detail_id").val(obj.detail_id);
$(".item_code").val(obj.item_code);
$(".price").val(obj.price);
$(".weight").val(obj.weight);
}
}
});
}
$(document).ready(function() {
$('.header_id').on('keyup', function() {
getdHeaderid($(this));
});
});
</script>
Your question wording is pretty hard to understand, but taking my best guess as to what you're looking for - you want a table row for each element from data. If so, here is how you can do that.
var data = [{
header_id: "TR100001",
detail_id: "2",
item_code: "SPH001",
price: "4000",
weight: "2"
},
{
header_id: "TR100001",
detail_id: "3",
item_code: "SPH002",
price: "4500",
weight: "2"
},
{
header_id: "TR100001",
detail_id: "4",
item_code: "SPH003",
price: "30000",
weight: "2"
},
{
header_id: "TR100001",
detail_id: "5",
item_code: "SPH004",
price: "45000",
weight: "2"
}
];
function getdHeaderid(header_id) {
// make ajax call...
// ...
// success callback (data) {
var tableHTML = [];
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var newRow = $(".clone-row").clone(true);
newRow.removeClass("clone-row");
newRow.find(".header_id").val(obj.header_id);
newRow.find(".detail_id").val(obj.detail_id);
newRow.find(".item_code").val(obj.item_code);
newRow.find(".price").val(obj.price);
newRow.find(".weight").val(obj.weight);
tableHTML.push(newRow);
}
$("#dataTable2 tr:not(.clone-row)").remove();
$("#dataTable2").append(tableHTML);
// } end success callback
}
getdHeaderid();
.clone-row {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="buy_transaction">
<tbody id="dataTable2">
<tr class="clone-row">
<td><input type="checkbox" class="chk" name="chk[]" value="<?php echo $detail->detail_id; ?>"></td>
<td><input type="text" name="detail_id[]" class="detail_id form-control" value="<?php echo $detail->detail_id ;?>" size="1"> </td>
<td><input type="text" width="10" class="item_code form-control" id="item_code" name="item_code[]" value="<?php echo $detail->item_code; ?>"></td>
<td><input type="text" class="header_id1 form-control" id="header_id" name="header_id[]" value="<?php echo $detail->header_id; ?>" readonly></td>
<td><input type="text" class="price form-control" id="price" name="price[]" value="<?php echo $detail->price; ?>" readonly></td>
<td><input type="text" class="weight form-control" id="weight" name="weight[]" placeholder="0" value="<?php echo $detail->weight; ?>"></td>
</tr>
</tbody>
</table>
Your table only has a single row within which you can assign data. Also, you should wrap your table data tags with the <tr></tr> tags, to indicate that this is a distinct row in the table. When iterating through your data, you should be creating new rows, for each set of data in your json. Something like this:
var table = document.getElementById("buy_transaction");
for(var i = 0; i<data.length; i++) {
var obj = data[i];
var row = table.insertRow(i);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(1);
var cell4 = row.insertCell(1);
var cell5 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML(obj.header_id);
cell2.innerHTML(obj.detail_id);
cell3.innerHTML(obj.item_code);
cell4.innerHTML(obj.price);
cell5.innerHTML(obj.weight);
};
This way you're for each iteration of the for loop, you're creating a new row for your table and you're inserting the proper values.
I have short problem.
In my form I have multi-input and where the user change the values.
<div id="contenu">
<h2>Renseigner ma fiche de frais du mois <?php echo $numMois."-".$numAnnee ?></h2>
<form method="POST" action="index.php?uc=gererFrais&action=validerMajFraisForfait">
<div class="corpsForm">
<fieldset>
<legend>Eléments forfaitisés
</legend>
<table width=100%>
<tr>
<td>Libelle</td>
<td>Nombre</td>
<td>Montant unitaire</td>
<td>Montant total</td>
</tr>
?>
<tr>
<td width=20%><?php echo $libelle ?></td>
<td width=20%><input type="text" id="<?php echo 'idFrais'.$incr; ?>" name="lesFrais[<?php echo $idFrais?>]" size="10" min="0" autocomplete="off" maxlength="30" value="<?php echo $quantite?>" onkeyup="calculer(this)">
<td width=20%><input type="text" id="<?php echo 'montant'.$incr; ?>" value="<?php echo $montant ?>" disabled></td>
<td id='subtotal<?php echo $incr;?>' width=20%><?php echo $quantite*$montant; ?></td>
</tr>
<?php
$incr ++;
}
?>
<tr>
<td colspan="3">Total : </td>
<td></td>
</tr>
</table>
</fieldset>
</div>
<div class="piedForm">
<p>
<input id="ok" type="submit" value="Valider" size="20" />
<input id="annuler" type="reset" value="Effacer" size="20" />
</p>
</div>
</form>
I want add one line where the total of the col "Montant total" has executed.
Exemple :
And the calcul has been executed direct, no refresh.
First of all instead of using ID for subtotal use Class - subtotal. Then all you have to do is query all of those elements using
querySelectorAll('.subtotal') or $('.subtotal')
and store the resulting array (in jQuery a jQuery object like array) into a variable. Then add events to the quantity input fields and call a function which will iterate over all of the elements in the previously stored array and convert the text stored in them (which was generated using your calculer function) which can be accessed using
subtotal[index].innerText
and parse it into Number using
Number(subtotal[index].innerText)
and check if the resulting number is NaN (Not a Number) or not using isNaN() function. If not add to a local total variable and write the result in the end.
Hope this helps.
Here is the code -
function CalculateTotal(e) {
var subtotal = querySelectorAll('.subtotal');
var subtotalCount = subtotal.length;
var subtotalValue;
var total = 0;
for (var i = 0; i < subtotalCount; i++) {
subtotalValue = Number(subtotal[i].textContent);
if (!isNaN(subtotalValue)) total += subtotal;
}
// Set the total element's textContent here.
}
Call the above function at the end of your calculer function.
I've got an error says failed, whenever I check this code I feel there is nothing wrong with my code. Please help me, as I'm only a beginner. There are forms, javascript, and php.
<?php
$species=""; //declare variable to assign table record data
$age= "";
$sex="";
$location="";
$comment="";
require('connectdb.php');
$record=$_REQUEST['id' ];
$query="SELECT * FROM usersform WHERE id = $record "; // listing reservation record
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$species= $row['species']; //retrieve table record and assign to variable
$age= $row['age'];
$location= $row['location'];
$comment= $row['comment'];
if (isset($_POST['submit']))
{
//get data from reservation form
$spec=$_POST['species'];
$eage=$_POST['age'];
$gender=$_POST['gender'];
$elocation=$_POST['location'];
$ecomment=$_POST['comment'];
//update data to table
$query=" UPDATE `usersform` SET
`species` ='$spec',
`age`='$eage',
`location`='$elocation',
`comment`='$ecomment',
WHERE usersform= $record
";
$qresult = mysql_query($query);
if ($qresult){
/*echo '<script type="text/javascript">
window.location = "http://www.example.com/";
</script>';*/
echo '<script type="text/javascript"> window.location="gallery.php";</script>';
#header("location:gallery.php"); // redirect to list
}
else
{
echo "<script type='text/javascript'>alert('failed!')</script>";
}
}
?>
Here is my form code:
<h2>Edit/Update Reservation Record </h2>
<form name="Form" method="Post" onsubmit="return(validateForm());" onreset="cancel();">
<table cellspacing="2" cellpadding="2">
<tr>
<td>species: </td>
<td><input type="text" name="species" size="35" value="<?php echo $species; ?>"/></td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" name="age" maxlength="15" size="15" value="<?php echo $age; ?>"/></td>
</tr>
<tr>
<td>sex:</td>
<td><input type="radio" name="gender" value="male" value="<?php echo $sex; ?>"/>Male <input type="radio" name="gender" value="female" value="<?php echo $sex; ?>"/>Female</td>
</tr>
<tr>
<td>location:</td>
<td><input type="text" name="location" size="35" value="<?php echo $location; ?>"/></td>
</tr>
<tr>
<td>comment:</td>
<td><input type="text" name="comment" size="50" value="<?php echo $comment; ?>"/></td>
</tr>
<tr>
<td><input type="submit" value="Update" name="submit" /></td>
<td><input type="reset" value="Cancel" name="reset" /></td>
</tr>
</table>
</form>
Here is my javascript:
function validateForm() {
if( document.Form.species.value == "" )
{
alert( "Please insert species." );
document.Form.Name.focus() ;
return false;
}
if( document.Form.age.value == "" ||isNaN( document.Form.age.value ) )
{
alert( "Please insert age." );
document.Form.age.focus() ;
return false;
}
if( document.Form.location.value == "" )
{
alert( "Please insert location." );
document.Form.Name.focus() ;
return false;
}
if( document.Form.comment.value == "" )
{
alert( "Please insert comment." );
document.Form.Name.focus() ;
return false;
}
}
function cancel()
{
window.location.href="gallery.php";
}
the update syntax is incorrect.. this is the correct sql syntax
$query=" UPDATE `usersform` SET
`species` ='$spec',
`age`='$eage',
`location`='$elocation',
`comment`='$ecomment'
WHERE usersform= $record
";
change your update query to this
$query=" UPDATE `usersform` SET
`species` ='$spec',
`age`='$eage',
`location`='$elocation',
`comment`='$ecomment'
WHERE id= $record
";
$qresult = mysql_query($query) or die(mysql_error());
Note: Learn mysqli_ or P.D.O as mysql is depriciated