Add Row Button adds PHP cell with Select2 option - javascript

Sorry about the Q form but I couldn't find a better way to explain it.
I have a view table that have drop down form that retrieves its options from the DB to be inserted, and it have an add button to add new row to insert.
But the drop down works on Select2 forms, and it's included in the table, so every time I try to add new row it gives it the same id as the previous one and that conflicts with the JS for the Select2 as it needs to get special id for every drop down I made with it.
here's the table and the add button code
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="tab_logic">
<thead>
<tr>
<th>Brand Name</th>
<th>Item Name</th>
<th>Model Number</th>
<th class="col-md-2">Item Description</th>
<th>Part Number</th>
<th>Unit</th>
<th class="col-md-1">QTY</th>
<th class="col-md-1">Unit Price (SR)</th>
<th class="col-md-1">Total Price (SR)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div class="form-group">
<?php
$query = $con->query("SELECT products_itemDescription FROM pruc_products"); // Run your query --> For Item Desc.
echo '<select class="form-control" id="DescriptionS2forms" name="itemDescription">'; // Open your drop down box
echo '<option value="" selected="selected" disabled></option>'; //Empty Value for VALIDATION
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';
}
echo '</select>';// Close your drop down box
?>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestQTY" required>
</div>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td class="col-md-1" id="deleteBtn">
<a class="btn btn-default deleteBtn">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- End of 3rd Row -->
<div class="row">
<a id="add_row" class="btn btn-default pull-right">Add</a>
</div>
And the JS for the add button and select2 function:
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
var x = '[{<td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div class="form-group"> <?php $query = $con->query('SELECT products_itemDescription FROM pruc_products'); echo '<select class="form-control" id=DescriptionS2forms'.(i+1).'" name="itemDescription">'; echo '<option value="" selected="selected" disabled></option>'; while($row = $query->fetch(PDO::FETCH_ASSOC)) {echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';} echo '</select>'; ?> </div></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div><input class="form-control" type="number" name="requestQTY" required></div></td> <td><div><input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required></div></td> <td><strong>Record</strong></td> <td class="col-md-1" id="deleteBtn"> <a class="btn btn-default deleteBtn">Delete</a></td>}]';
$('#tab_logic').append('<tr id="addr' + (i + 1) + '">' + x + '</tr>');
i++;
});
$("#SupplierS2forms, #ProjectS2forms, #WHS2forms, #DescriptionS2forms").select2(); });
in the PHP option it gives the id="DescriptionS2forms"
so I need to add a number for the id so I can use it in the Select2 Function as it doesn't accept same id
Example
id="DescriptionS2forms1" AND id="DescriptionS2forms2"

Related

How to auto calculate the html table using jQuery?

Can someone or anybody help me on how to auto calculate total price in the table? Please see the image below:
Here's my code (I will included only the code that I used in the Image):
HTML:
<div class="col-12">
<div class="col drop">
<table name="services">
<tr name="services">
<td>
<select class="form-control serv" name="txt-service" id="txt-service"> //dynamic services (from database)
<option value="" readonly>--- Select Service ---</option>
<?php include "include/connect.php";
$sql="SELECT service_id,services,price FROM tbl_serviceoffered";
foreach ($con->query($sql) as $row){
echo "<option value=$row[service_id] data-price=$row[price] data-service=$row[services]>$row[services]</option>";
}
echo "</select>";
?>
</td>
<td><input type="hidden" style="text-align:right" class="form-control" name="service" id="showservice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="price" id="showprice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="item_total" id="item_total"></td>
<td><button class="btn btn-primary" name="add">Add</button></td>
</tr>
</table>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover table-bordered table-striped" name="transactions" id="transactions">
<thead>
<th></th>
<th style="text-align:center">Service Name</th>
<th style="text-align:center">Service Price</th>
<th style="text-align:center">Service Total</th>
</thead>
<tbody>
</tbody>
</table>
<td colspan="2" class="tr"> </td>
<div class="text-right">
<tr>
<td><b>Total</b></td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" style="text-align:right; font-weight:bold" class="form-control" name="grand_total" id="grand_total" placeholder="Total"></td>
</tr>
<tr>
<td>Cash Tendered</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="cashtendered" placeholder="Cash Tendered"></td>
</tr>
<tr>
<td>Change</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="change" placeholder="Change"></td>
</div>
</div>
</div>
<div class="text-right">
<button type="button" class="btn btn-primary btn-icon icon-right" name="btnSaveTransaction" id="btnSaveTransaction"><i class="fas fa-file-invoice"></i> Process Payment</a>
</div>
JS:
var id = 1;
/*Assigning id and class for tr and td tags for separation.*/
$("button[name=add]").click(function() {
var newid = id++;
$("table[name=transactions]").append('<tr id="'+newid+'">\n\
<td style="text-align:center;"><a class="btn btn-primary" href="javascript:void(0);" id="remove">Remove</a></td>\n\
<td width="100px" style="display:none;">' +newid+ '</td>\n\
<td style="text-align:center; display:none;" class="num'+newid+'">' + $("#txt-transact_num").val() + '</td>\n\
<td style="text-align:center; display:none;" class="date'+newid+'">' + $("#txt-transact_date").val() + '</td>\n\
<td style="text-align:center; display:none;" class="patientid'+newid+'">' + $("#txt-patient_id").val() + '</td>\n\
<td style="text-align:center;" class="serv'+newid+'">' + $("#showservice").val() + '</td>\n\
<td style="text-align:center; display:none;" class="servid'+newid+'">' + $(".serv option:selected").val() + '</td>\n\
<td style="text-align:right;" class="price'+newid+'">₱' + $("#showprice").val() + '</td>\n\
<td style="text-align:right;" name="txt" class="totalprice'+newid+'">₱' + $("#item_total").val() + '</td>');
$("#txt-service").val("");
$("#showprice").val("");
$("#item_total").val("0.00");
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("tbody").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#grand_total").val(sum.toFixed(2));
}
$("#transactions").on('click', '#remove', function() {
$(this).parent().parent().remove();
calculateSum();
});
As you can see, in the image above, when I add or pick some services that shows the total each of them, the textbox "total" fetch 0.00 only.
I'm still beginner in this programming language. I hope everyone can help me for our Capstone Project. Thank you!

How can I check a checkbox depending on what row using jQuery?

What I have tried is to make a checkbox when clicked it automatically checks the other checkbox from it's row but when I tried to check the other rows, it does not work. I've tried to make a loop but instead of checking each, it checks all. I hope someone can help me. Thank you so much in advance!
Here is my whole code, I am using dataTables
$(document).ready(function() {
$('#is_checked_status').on('click', function() {
var checkAll = this.checked;
$('input[id=subCheckbox]').each(function() {
this.checked = checkAll;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Emailed Data for approval
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables">
<thead>
<tr>
<th> Control Number </th>
<th> Tools Specification </th>
<th> Supplier </th>
<th>
<center> Status </center>
</th>
<th>
<center> Select data to approve </center>
</th>
<th>
<center> ID </center>
</th>
</tr>
</thead>
<?php
$con->next_result();
$result = mysqli_query($con,"CALL GetAllRequestedTools()"); ?>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td><a href='edit_tools_approval.php?
ID=".$row['ID']."' style='color:red;'>" .
$row['reg_input'] . "</a></td>";
echo "<td>" . $row['reg_tools_spec'] . "</td>";
echo "<td>" . $row['reg_supplier'] . "</td>";
?>
<td>
<center>
<label data-id="<?php echo $row['ID'];?>" class="statusButton <?php echo ($row['req_stats'])? 'label-success': 'label-danger'?>">
<?php echo ($row['req_stats'])? 'Approved' : 'Pending'?>
</label>
</center>
</td>
<td>
<center>
<input name="chk_status[]" id="is_checked_status" type="checkbox" value="<?php echo $row['req_stats'];?>">
</center>
</td>
<td>
<center>
<input name="chk_id[]" type="checkbox" id="subCheckbox" value="<?php echo $row['ID'];?>">
</center>
</td>
<?php
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Ids are singular so you can not use an id multiple times. Change all of the ids to a class.
After you remove the ids and swap it to a class. You will need find the row the checkbox is in. And then select all the checkboxes in that row.
$(document).ready(function() {
$('.is_checked_status').on('click', function() {
var checkAll = this.checked;
// find the row
var row = $(this).closest("tr");
// find the checkboxes in the row
row.find('input.subCheckbox').each(function() {
this.checked = checkAll;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox" class="is_checked_status" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
</tr>
<tr>
<td><input type="checkbox" class="is_checked_status" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
<td><input type="checkbox" class="subCheckbox" /></td>
</tr>
</table>

How can I sum the price of the item that I selected from my dropdown that retrieved in the database

I'm trying to sum the price after selecting an item in the dropdown, but it only displays NaN. The value of dropdown are retrieved from MySQL database
<?php
//database connection here
?>
<table border=" 1">
<thead>
<tr>
<th>Component</th>
<th>Item Name</th>
<th>Price </th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>
<?php
//Retrieving CPU table
$query = $conn->query("SELECT * FROM cpu");
echo '<select onChange = parseFloat($("#cpuprice").val($(this).find("option:selected").attr("cpuprice")))>';
echo "<option>---select your CPU---</option>";
while ($obj = $query->fetch_object()) {
echo '<option cpuprice = "' . $obj->price . '" >' . $obj->cpuname . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output class="form-control prc" id="cpuprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<?php
//Retrieving GPU table
$query = $conn->query("SELECT * FROM gpu");
echo '<select onChange = parseFloat($("#tpuprice").val($(this).find("option:selected").attr("gpuprice")))>';
echo "<option>---select your GPU---</option>";
while ($obj = $query->fetch_object()) {
echo '<option gpuprice = "' . $obj->price . '" >' . $obj->gpuname . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output class="form-control prc" id="tpuprice" disabled value="">
</td>
</tr>
</tbody>
</table>
this is the jQuery that I used I don't know if this is right but I search everywhere and NaN is the best result I got so far, sorry I'm just new to using JavaScript or jQuery
<span class="totalprice">Total: </span>
<script>
var total = 0;
$('select').change(function() {
var cpu = ($('#totalprice').val($(this).find('option:selected').attr('cpuprice')))
var gpu = ($('#Totalprice').val($(this).find('option:selected').attr('gpuprice')))
total = parseFloat(cpu) + parseFloat(gpu);
$('.totalprice').text('₱' + total);
})
</script>
here is the picture, after selecting it just NaN:
You can check if the attr exist on not inside option because your first option doesn't have attr that's the reason its giving NaN so if doesn't exist just give value 0 else attr value .
Demo Code :
var total = 0;
$('select').change(function() {
//get value from cpu slect box check if attr there else take value 0
var cpu_price = $(".cpu").find('option:selected').attr('cpuprice') ? $(".cpu").find('option:selected').attr('cpuprice') : 0
$('#cpuprice').val(cpu_price)
//get value from gpu slect box check if attr there else take value 0
var gpu_price = $(".gpu").find('option:selected').attr('gpuprice') ? $(".gpu").find('option:selected').attr('gpuprice') : 0
$('#tpuprice').val(gpu_price)
total = parseFloat(cpu_price) + parseFloat(gpu_price);
$('.totalprice').text('₱' + total);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=" 1">
<thead>
<tr>
<th>Component</th>
<th>Item Name</th>
<th>Price </th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>
<select class="cpu">
<option>---select your CPU---</option>
<option cpuprice="1222">Soemthing</option>
<option cpuprice="1000">Soemthing1</option>
</select>
</td>
<td>
<output class="form-control prc" id="cpuprice" disabled value="" />
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<select class="gpu">
<option>---select your GPU---</option>
<option gpuprice="1200">Somehingg</option>
<option gpuprice="120">Somehingg1</option>
</select>
</td>
<td>
<output class="form-control prc" id="tpuprice" disabled value="" />
</td>
</tr>
</tbody>
</table>
<span class="totalprice">Total: </span>

Retrive data using PHP and Ajax

Here I am trying to fetch data from Mysql database using PHP and Ajax. My problem is, when I type the Test ID on test_id text box, just it immediatetly shows the Test Name according to the Test ID on test_name text box.
Here I used the function called checkname. In console just it show the Test Name but does not show in the test_name text box.
Here is the HTML code.
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control" type="text" style="width:200px" id="test_id[]" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>
<td> <input type="text" style="width:300px" class="form-control text-right form-amt" readonly="" id="test_name[]" > </td>
<td> <input type="text" style="min-width:100px" class="form-control text-right form-amt" readonly="" id="amount[]"> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
Here is the Ajax code;
<script>
function checkname()
{
var test_id = document.getElementById("test_id[]").value;
$.ajax({
type: 'post',
url: "adminquery/fetch_test_name.php", // request file the 'check_email.php'
data: {'test_id': test_id, },
success: function (data) {
$("#test_name[]").html(data);
}
});
}
</script>
Here is the PHP code
<?php
include('../auth/dbconnection.php');
$output='';
$sql="SELECT * from testings where test_id='".$_POST['test_id']."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$name= $row["testing_name"];
$output.=' <input type="text" readonly="" id="test_name[]" value="'.$name.' "> '.$name.' ';
}
echo $output;
?>
Anyone could help me may highly appreciated.
First lose the brackets in the id.
<input id="test_name" type="text" value="other" />
Then use .val() instead of .html()
$("#test_name").val("something")

Create an array of text fields using data from a database and use the values from the fields to do calculate

I would like to fetch items and item prices from database and use it to create an array of input fields for quantity and amount. Then use Jquery to automatically fetch the values of quantity as I type and multiply it by the price to display the amount in the amounts field for each item.
At the same time, the totals value (which is sum of all amounts) should also be displayed.
This is restricted to only the items that have been checked (selected).
<table class="form" id='tab1e'>
<tr>
<th> </th>
<th style="text-align: left;">Material Name</th>
<th style="text-align: center;">Quantity</th>
<th style="text-align: center;">Unit Price</th>
<th style="text-align: center;">Amount</th>
<th style="text-align: center;">Currency</th>
</tr>
<?php
foreach($database_result as $value){
?>
<tr>
<td>
<input type="checkbox" name="checkboxes[]" value="<?php echo $row['price']."".$row['item_name'] ?>">
</td>
<td style="width: 150px">
<?php echo $row['item_name'] ?>
</td>
<td>
<input name="qnty[]" id="qnty">
</td>
<td>
<input name="price" class="form-control" value="<?php echo $row['price']) ?>" id="price">
</td>
<td>
<input name="total_amount[]" class="text form-control" readonly="readonly" id="total_amount">
</td>
</tr>
<?php } ?>
<tr>
<td>Total Amount</td>
<td style="text-align: right;" id="totalpop"></td>
<td></td>
</tr>
</table>
First thing is the inputs should have different ids.
Now, you can use onchange event to call a function when input value changes. You can use plain javascript for that. Here's an example:
<html>
<body>
<script>
function o(id) {
return document.getElementById(id);
}
function updatePrice(id) {
if (!o('qnty'+id).value.match(/^[0-9]+$/)) {
alert('Invalid quantity');
o('total'+id).value = '0';
return false;
}
// Similar check for price
o('total'+id).value = parseInt(o('qnty'+id).value) * parseFloat(o('price'+id).value);
}
</script>
<input name="qnty[]" onchange="updatePrice('1')" id="qnty1">
<input name="price" value="1" onchange="updatePrice('1')" id="price1">
<input name="total_amount[]" id="total1">
</body>
</html>
The 1 corresponds to row number, so you would need to change your PHP code so it has a row number (can be just a simple $i=1; before the loop and $i++; in the end of every loop iteration).

Categories

Resources