How to calculate the row of the table using javascript - javascript

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>

Related

How to get dynamic values by selection (mysql database) in multiple table rows

I have created an invoice table in which rows are created by pressing 'Add' button. In addition, items price are being displayed into first row of the input value by selection. Everything is fine but when I come to the second row by pressing Add row, price value isn't working by pressing selection.
Here is the table code:
<div class="box pattern pattern-sandstone">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody id="customFields">
<tr>
<td> 1 </td>
<td>
<?php include "db_conn.php";
$query_order_to = "SELECT * from gs_items ORDER BY item_name ASC";
$result_order_to = $conn->query($query_order_to); ?>
<select name="selected_item" id="selected_item" onchange="myItemPrice()" data-placeholder="Item Name" >
<option value="">Select Item</option>
<?php
while($rows=mysqli_fetch_assoc($result_order_to))
{ ?>
<option data-price='<?php echo $rows['price']; ?>' value='<?php echo $rows['Id']; ?>'> <?php echo $rows['item_name']; ?></option>
";
<?php } ?>
</select>
</td>
<td><textarea style="min-width: 90%;"></textarea></td>
<td> <input type="text" name="getprice" style="font-size: 12px; color: #333333;" id="getprice" disabled></td>
<td><input type="number" ></td>
<td><input type="number" ></td>
<td><button onclick="addRow();">Add</button></td>
</tr>
</tbody>
</table>
</div>
Here is Javascript + PHP:
<script>
function findAddress(){
var address = $('#select_data').find(':selected').data('address');
$('#getcustomeraddress').val(address);
}
</script>
<script>
function myItemPrice(){
var price = $('#selected_item').find(':selected').data('price');
$('#getprice').val(price);
}
</script>
<?php
$conn = mysqli_connect('localhost','root','','gs');
function fill_unit_select_box($conn)
{ $query_item = "SELECT * from gs_items ORDER BY item_name ASC";
$result_item = $conn->query($query_item);
$x = 1;
foreach($result_item as $rows)
{ echo '<option data-prices'.$x++.'="'.$rows['price'].'" value="'.$rows['Id'].'">'.$rows['item_name'].'</option>';
}
} ?>
<script>
function addRow()
{ var table = document.getElementById("customFields");
var i = 1;
while (i <= table.rows.length) {
i++;
}
var html = '';
html += '<tr>';
html += '<td >'+i+'</td>';
html += '<td><select name="selected_items'+i+'" id="selected_items'+i+'" onchange="myItemPrices()" data-placeholder="Item Name" ><option value="">Select Item</option>';
html += ' <?php echo fill_unit_select_box($conn); ?>
</select></td>';
html += '<td > <textarea style="min-width: 90%;"></textarea></td>';
html +='<td > <input type="number" name="getprices'+i+'" style="font-size: 12px; color: #333333;" id="getprices'+i+'" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td><button onclick="remove();">Remove</button></td>';
html +='</tr>';
$('#customFields').append(html);
}
function myItemPrices(){
var prices = $('#selected_items'+i+'').find(':selected').data('prices'+i+'');
$('#getprices'+i+'').val(prices); }
</script>
I have fixed a number of bugs in your original codes
The $x++ is not necessary for the function fill_unit_select_box($conn)
You should pass the i to the javascript myItemPrices function, for example as var1 (so will be myItemPrices(var1)):
Please find below a fully working one:
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<div class="box pattern pattern-sandstone">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Item</th><th>Description</th><th>Price</th><th>Qty</th><th>Total</th>
</tr></thead>
<tbody id="customFields">
<tr>
<td>1</td><td >
<?php
$conn = mysqli_connect('localhost','dbuser','dbpass','dbname');
$query_order_to = "SELECT * from gs_items ORDER BY item_name ASC";
$result_order_to = $conn->query($query_order_to); ?>
<select name="selected_item" id="selected_item" onchange="myItemPrice()" data-placeholder="Item Name" >
<option value="">Select Item</option>
<?php
while($rows=mysqli_fetch_assoc($result_order_to))
{ ?> <option data-price='<?php echo $rows['price']; ?>' value='<?php echo $rows['Id']; ?>'> <?php echo $rows['item_name']; ?></option>";
<?php } ?> </select> </td>
<td ><textarea style="min-width: 90%;"></textarea></td>
<td ><input type="text" name="getprice" style="font-size: 12px; color: #333333;" id="getprice" disabled></td>
<td ><input type="number" ></td>
<td ><input type="number" ></td>
<td><button onclick="addRow();">Add</button></td>
</tr>
</tbody>
</table>
</div>
<script>
function findAddress(){
var address = $('#select_data').find(':selected').data('address');
$('#getcustomeraddress').val(address);
}
</script>
<script>
function myItemPrice(){
var price = $('#selected_item').find(':selected').data('price');
$('#getprice').val(price);
}
</script>
<?php
$conn = mysqli_connect('localhost','dbuser','dbpass','dbname');
function fill_unit_select_box($conn)
{
$query_item = "SELECT * from gs_items ORDER BY item_name ASC";
$result_item = $conn->query($query_item);
$x = 1;
foreach($result_item as $rows)
{ echo '<option data-prices="'.$rows['price'].'" value="'.$rows['Id'].'">'.$rows['item_name'].'</option>';
}
} ?>
<script>
function addRow()
{ var table = document.getElementById("customFields");
var i = 0;
while (i <= table.rows.length) {
i++;
}
i=i-1;
var html = '';
html += '<tr>';
html += '<td >'+i+'</td>';
html += '<td><select name="selected_items'+i+'" id="selected_items'+i+'" onchange="myItemPrices(' + i +')" data-placeholder="Item Name" ><option value="">Select Item</option>';
html += ' <?php echo fill_unit_select_box($conn); ?>
</select></td>';
html += '<td > <textarea style="min-width: 90%;"></textarea></td>';
html +='<td ><input type="text" disabled name="getprices'+i+'" style="font-size: 12px; color: #333333;" id="getprices'+i+'" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td><button onclick="remove();">Remove</button></td>';
html +='</tr>';
$('#customFields').append(html);
}
function myItemPrices(var1){
i=var1;
var prices = $('#selected_items'+i+'').find(':selected').data('prices');
$('#getprices'+i+'').val(prices); }
</script>

My poll results for my coloured bars don't work

I am trying to make a poll with two pink bars to show the percentages of the results. I made my percentage bars images, although when I used the poll, they stay the same size and don't get any smaller/bigger according to their %. How should I change the code so that the % bars change their lengths?
HMTL code:
<html>
<head>
<script>
function getVote(int) {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("poll").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br>
No: <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
PHP file:
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td><img src="images/poll.png"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td><img src="images/poll.png"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
You should not use image for indicating progress. Use <progress> or other HTML element with CSS.
I have changed your poll_vote.php file to use <progress> element.
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$yesProgress = 100*round($yes/($no+$yes),2);
$noProgress = 100*round($no/($no+$yes),2);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<progress id="file" max="100" value="<?= $yesProgress ?>">
<?= $yesProgress ?>
</progress>
<?= $yesProgress ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<progress id="file" max="100" value="<?= $noProgress ?>">
<?= $noProgress ?>
</progress>
<?= $noProgress ?>%
</td>
</tr>
</table>
Refer below Links:
HTML Element
Bootstrap 4 Progress Bars

php html javascript wrong result

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;
}

I'm trying to pull data from database into selectboxes

I'm trying to pull data from database into selectboxes, but when the data is pulled it goes into one 'td' and not into separate td's. I'm trying to achieve result as shown below
but I keep getting this result
here is my code
<?php
$data_array = array();
$result2 = mysql_query("SELECT * FROM `firefightersonscene`
JOIN `firefighterinfo` ON `firefightersonscene`.`FireFighterInfo_fighterID` = `firefighterinfo`.`fighterID`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID`
WHERE `IncidenceOfFire_incidentID`='$getIncID' ORDER BY `firstName`");
if(mysql_num_rows($result2) > 0)
{
while($rows2 = mysql_fetch_object($result2))
{
$data_array[] = $rows2;
}
}
?>
<form action="core_viewfireoccurrence.php?incidentID=<?php echo $rows->incidentID; ?>" method="post" class="view_occurrence_form">
<table id="myTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td class="count">1</td>
<td>
<?php
foreach($data_array as $rows2):
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
endforeach;
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" id="addVar" value="Add Item"/>
</tr>
</tfoot>
</table>
</form>
JS CODE
<script type="text/javascript">
$('form').on('click', '.removeVar', function(){
$(this).closest('tr').remove();
$('.count').each(function(i){
$(this).text(i + 1);
});
});
//add a new node
$('#addVar').on('click', function(){
var varCount = $('#myTable tr').length - 1;
$node = ['<tr>',
'<td class="count">'+varCount+'</td>',
'<td><select name="fireman[]" class="ctlGroup" required>',
'<option value=""></option>',
'<?php require("php/fireman_list.php"); ?>',
'</select></td>',
'<td><input type="button" value="X" class="removeVar"/>',
'</td></tr>'].join('\n');
$('#myTable > tbody:last').append($node);
});
</script>
You need to put your whole table row in the loop. You will also need to add a variable to count the row number for you.
<?php
$row =1;
foreach($data_array as $rows2):
?>
<tr>
<td class="count"><?php echo $row; ?></td>
<td>
<?php
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
<?php
$row++;
endforeach;
?>

Delete table row with Javascript

Currently I have a table for information called episodes. The table has fields consisting of title, air date, episode number, and plot. I use javascript to clone the fields and also to delete them. My problem is the delete function deletes only the title, airdate, and episode number; however the plot box remains. The problem from what I can tell is that the plot is wrapped in a different <tr></tr> tag. How do I get the delete function to delete both sets?
Here is the table
<table id="template" style="display: none">
<tr class="line">
<td width="50%">
<label><?php _e('Episode Title'); ?></label>
<p>
<input type="text" name="episode_title[]" id="episode_title[]" value="" class="title regular-text" style="width:100%;" />
</p>
</td>
<td width"10%">
<label><?php _e('Airdate'); ?></label>
<p>
<input type="text" name="episode_airdate[]" id="episode_airdate[]" value="" class="airdate regular-text" style="width:100%" />
</p>
</td>
<td width="10%">
<label><?php _e('Season:'); ?></label>
<p>
<?php
for($i=1; $i<=50; $i++)
$season_nums[]=$i;
echo '<select name="episode_season[]" select id="episode_season[]" class="season regular-text" style="100%">';
echo '<option value="">' . __("Season" ) . '</option>';
foreach($season_nums as $season_num){
$selected = '';
echo '<option value="' . $season_num . '" ' . $selected . '>' . $season_num . '</option>';
}
echo '</select>';
?>
</p>
</td>
<td width="10%">
<label><?php _e('Episode:'); ?></label>
<p>
<input type="text" name="episode_number[]" id="episode_number[]" value="" class="number regular-text" style="width: 100%" />
</p>
</td>
<td width="10%" class="commands">
<a rel="delete" class="button">-</a> <a rel="add" class="button">+</a>
</td>
</tr>
<tr class="line2">
<td width="100%">
<label><?php _e('Plot:'); ?></label>
<textarea name="episode_plot[]" id="episode_plot[]" class="plot regular-text"value="" cols="100%" rows="10" tabindex="4" ><?php echo $_POST['episode_season'] ?></textarea>
</td>
</tr>
Here is the JavaScript
// Delete the "-" button in first row
$('#attachments tr:first-child .commands a[rel="delete"]').remove();
}
function items_add()
{
obj = $('#template tr').clone().appendTo('#attachments');
lines++;
if (arguments.length > 0) {
options = arguments[0];
$('.title', obj).val( options.title );
$('.airdate', obj).val( options.airdate );
$('.season', obj).val( options.season );
$('.number', obj).val( options.number );
$('.plot', obj).val( options.plot );
}
}
$('#attachments').delegate('.commands a', 'click', function()
{
var action = $(this).attr('rel');
var confirm_delete = true;
// Add action
if ('add' == action) {
items_add();
}
// Delete action
if ('delete' == action) {
// La TR en la tabla
var oTr = $(this).parent().parent();
var episode_name = $('.title', oTr).val();
var episode_airdate = $('.airdate', oTr).val();
var episode_season = $('.season', oTr).val();
var episode_number = $('.number', oTr).val();
var episode_plot = $('.plot', oTr).val();
if (episode_name != '' || episode_number != '' || episode_plot != '') {
if ( !confirm('Are you sure you want to delete ' + episode_name + '?') ) {
confirm_delete = false;
}
}
if (confirm_delete) {
oTr.remove();
lines--;
}
}
});
$(document).ready(function()
{
items_init();
});
})(jQuery);
Your help will be greatly appreciated
Change this line
var oTr = $(this).parent().parent();
to
var oTr = $(this).closest("tr");
Then use oTr.remove()
IDEA:
in php generate a random number like
$rand = time() * rand();
echo it on the line rows
<tr class="line" data-row="<?php echo $rand; ?>">
and
<tr class="line2" data-row="<?php echo $rand; ?>">
Using your delete function when someone clicks the link
var oTr = $(this).closest("tr");
var data-row =$(oTr).attr('data-row');
$('tr[data-row=' + data-row + ']').remove();
the idea is have a unique string to identify tr with line and line2 classes

Categories