Getting id from append table and use it in arithmetic javascript - javascript

I'm trying to get the id from append table and use it in arithmetic.
Here's the modal where i append the table and its in php
<tbody>
<tr class="item-row" id="item-row" onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' id='productUse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='productMsrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;' id='cost'><textarea rows='4' cols='10' name='Dealerphp' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td</td></tr>";
}
?>
</tbody>
here's the append javascript.
<script type="text/javascript">
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea class="productid" id="prc" value="'+ value +'</textarea></td><td class="item-name"><textarea class="productuse" id="productuse" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea class="description" id="description" value= "' + value2 +' </textarea></td><td class="item-name"><textarea class="msrp" id="msrp" value= "' + value3 + ' </textarea> </td><td class="item-name"><textarea class="cost" name="cost" id="'+ value4 + ' </textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty"></textarea></td><td class="item-name"><textarea id="price" class="price" name="price" disabled></textarea></td></tr>');
console.log(value4);
}));
});
});
</script>
and here's the arithmetic javascript to get the id, multiply to the column of qty and get the total.
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();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}

got it
function update_price() {
var row = $(this).parents('tr');
var a , w = 0;
var a = row.find('.cost').val().replace(/\,/g,'');
var w = row.find('.qty').val().replace(/\,/g,'');
var price = Number(a) * Number(w);
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}

Related

How to add HTML form fields based on JSON response data

I have a HTML form for products which contains initially a fields group (for the product components) of 2 rows and can add rows using a button with an onClick event to a js function addRow(). the code is:
<?php
$arrayNumber = 0;
for($x = 1; $x < 3; $x++) { ?>
<tr id="editRow<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">
<td style="padding-left:20px;padding-right: 20px;">
<div class="form-group">
<select class="form-control" name="editRawName[]" id="editRawName<?php echo $x; ?>" onchange="getRawData(<?php echo $x; ?>)">
<option value="">~~SELECT~~</option>
<?php
$rawSql = "SELECT * FROM raw_material WHERE status = 1";
$rawData = $connect->query($rawSql);
while($row = $rawData->fetch_array()) {
echo "<option value='".$row['raw_id']."' id='changeRaw".$row['raw_id']."'>".$row['raw_name']."</option>";
} // /while
?>
</select>
</div>
</td>
<td style="padding-left:20px;">
<div class="form-group">
<input type="number" name="editQuantity[]" id="editQuantity<?php echo $x; ?>" autocomplete="off" class="form-control" min="1"/>
</div>
</td>
<td>
<button class="btn btn-default removeRawRowBtn" type="button" id="removeRawRowBtn" onclick="removeRawRow(<?php echo $x; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
<?php
$arrayNumber++;
} // /for?>
Now, to edit a product I use a js function editProduct() to fetch the selected product data and return it as a JSON response to fill the product form fields. The editProduct function code part to grab and fill product fields is:
function editProduct(productId = null) {
if(productId) {
$("#productId").remove();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$('.div-loading').removeClass('div-hide');
$('.div-result').addClass('div-hide');
$.ajax({
url: 'action.php',
type: 'post',
data: {productId: productId},
dataType: 'json',
success:function(response) {
$('.div-loading').addClass('div-hide');
$('.div-result').removeClass('div-hide');
$(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.product_id+'" />');
// product name
$("#editProductName").val(response.product_name);
// category name
$("#editCategoryName").val(response.categories_id);
// quantity
$("#editProductQuantity").val(response.quantity);
// product unit
$("#editProductUnit").val(response.product_unit);
// sales margin
$("#editSalesMargin").val(response.sales_margin);
// status
$("#editProductStatus").val(response.status);
// Get the product components count
var totalComponents = response.total_components;
// Loop for every component
// Set the fields id that will contains the data
// Fill the fields with data
for (var x = 0; x<totalComponents; x++){
var idrawn = "#editRawName"+x.toString();
var idrawq = "#editQuantity"+x.toString();
var resri = "raw_id_"+x.toString();
var resqu = "rp_quantity_"+x.toString();
$(idrawn).val(response[resri]);
$(idrawq).val(response[resqu]);
}
The problem is: In case of a product with a total components of more than 2, I need to add rows to be filled with the components data.
First, I tried to launch the addRow() function before the last for loop in the editProduct function like this (didn't work):
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ addRow(); }
}
Then, I tried to simulate the click of the Add Component button that launch the addRow function using the solution posted here: How to simulate a click with JavaScript? and change the above code like this:
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ eventFire(document.getElementById('addRowBtn'), 'click'); }
}
but still no luck.
The code of addRow function is:
function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#rawTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;
if(tableLength > 0) {
tableRow = $("#rawTable tbody tr:last").attr('id');
arrayNumber = $("#rawTable tbody tr:last").attr('class');
count = tableRow.substring(3);
count = Number(count) + 1;
arrayNumber = Number(arrayNumber) + 1;
} else {
// no table row
count = 1;
arrayNumber = 0;
}
$.ajax({
url: 'action1.php',
type: 'post',
dataType: 'json',
success:function(response) {
$("#addRowBtn").button("reset");
var tr = '<tr id="row'+count+'" class="'+arrayNumber+'">'+
'<td style="padding-left:20px;padding-right: 20px;">'+
'<div class="form-group">'+
'<select class="form-control" name="rawName[]" id="rawName'+count+'" onchange="getRawData('+count+')" >'+
'<option value="">~~SELECT~~</option>';
$.each(response, function(index, value) {
tr += '<option value="'+value[0]+'">'+value[1]+'</option>';
});
tr += '</select>'+
'</div>'+
'</td>'+
'<td style="padding-left:20px;">'+
'<div class="form-group">'+
'<input type="number" name="quantity[]" id="quantity'+count+'" autocomplete="off" class="form-control" min="1" />'+
'</div>'+
'</td>'+
'<td>'+
'<button class="btn btn-default removeRawRowBtn" type="button" onclick="removeRawRow('+count+')"><i class="glyphicon glyphicon-trash"></i></button>'+
'</td>'+
'</tr>';
if(tableLength > 0) {
$("#rawTable tbody tr:last").after(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+count+'" />';
} else {
$("#rawTable tbody").append(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+tableLength+'" />';
}
$("#rawTable").after(comp);
}
});}
I was wandering if there is a way to get the result that I need.

how to set forloop for function in jquery

I was getting values in due to for each it was repeating same values
----------------------------------------------
<script type="text/javascript">
$(document).ready(function(){
var i=0;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select name='job_id"+i+"' class='form-control'><option value=''>Select the Job</option><?php
$mysql="select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id."'";
$result1 = mysql_query($mysql) or die(mysql_error());
while($roww = mysql_fetch_array($result1)){
$sql="select * from `ca_job_type` where `jtype_id`= '".$roww['job_type']."'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$row1['jtype_id'].' selected>'.$roww['job_id'].'-'.$row1['job_type_name'].'</option>';
} ?></select></td><td><input name='sac_hsc_code"+i+"' type='text' placeholder='description' class='form-control input-md' /> </td><td><input id='i"+i+"' type='text' placeholder='SAC/HSC Code' class='form-control input-md' ></td><td><select id='employee"+i+"' name='tax_id"+i+"' class='form-control'><option value=''>Please select</option><?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?></select></td><td class='appendData'></td><td><input name='amount"+i+"' type='text' class='form-control amt' id='amount"+i+"' class='form-control input-md' style='text-align: right;' ></td><td><input name='store"+i+"' type='hidden' id='store"+i+"' class='form-control input-md' style='text-align: right;' ></td>"
);
$("#employee"+i).change(function() {
var length = i;
var tax_id = $(this).find(":selected").val();
var dataString = 'tax_id='+ tax_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getEmployee.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
var employee = [employeeData];
----------I think I was getting the error because of this forEach ---------------------------
employeeData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.tax_type+'</td>';
data+= '<td align="right">'+item.tax_Percent+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
}
}
});
});
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
Same value was repeating in all places. I attached a screenshot for reference. Please help if anybody knows. Thanks in advance
try using following way using for loop
for(var i = 0 ;i <employeeData.length;i++){
$('.appendData').append('<tr><td colspan="4"></td><td align="right">'+employeeData[i].tax_type+'</td><td align="right">'+employeeData[i].tax_Percent+'</td></tr>')
}
If you are sure that your var employeeData has the good value, you can try this maybe :
// new empty data value
var data = "";
// you add one row each time you loop
$.each(employeeData, function(item) {
data += '<tr>';
data += '<td colspan="4"> </td>';
data += '<td align="right">'+item.tax_type+'</td>';
data += '<td align="right">'+item.tax_Percent+'</td>';
data +='</tr>';
});
// when it's over, you append your data where you want.
$('.appendData').append(data);
// An other idea could be to create a "container" div and do :
$('#mycontainer').html(data);
Is it what you are looking for?

Repeating jquery script in every row in table automatically

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

ajax get checkbox name which is an array

updated
I'm using while loop to display checkbox, the value of the checkbox is the amount. The codes can now display the total value when a checkbox is checked through the ajax function. During form submit, how do i obtain the $ID of checked value? As the name of the checkbox is not an array, i have no idea how to do that other way. Please help :'( Thanks in advance!
PHP:
<table>
<form name="listForm">
<?php
while($row=mysql_fetch_assoc($result)){
$ID = $row['ID'];
$amount = $row['amount'];
?>
<tr>
<td><input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" value="<?php echo $amount;?>" onclick="calculate();"></td>
</tr>
<?php
}?>
</table>
</form>
javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}
You need to get the "data-payment-id" attribute from the checkboxes that are clicked as well. I'd store them in an array, then json stringify it to be sent in your form.
Javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
var idList = [];
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
idList.push(document.listForm.payID[i].getAttribute('data-payment-id'));
}
}
document.getElementById('sum').value = sum;
document.getElementById('count').value = count;
document.getElementById('idList').value = JSON.stringify(idList);
return true;
}
And then for your form, update it to have the hidden inputs and the onsubmit function - here's what I was using for a test:
HTML Form:
<form name="listForm" action="aoeu.php" method="post" onsubmit="calculate()">
<input type='checkbox' name="payID" value='1' data-payment-id='aaa'> 1<br>
<input type='checkbox' name="payID" value='2' data-payment-id='bbb'> 2<br>
<input type='checkbox' name="payID" value='3' data-payment-id='ccc'> 3<br>
<input type='hidden' id='sum' name='sum'>
<input type='hidden' id='count' name='count'>
<input type='hidden' id='idList' name='idList'>
<button type='submit'>Submit</button>
</form>
Then just make sure to json_decode() the idList you get in your PHP post.
I have updated now. In your php code amend this line:
<input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" id="payment_id[]" onClick="calculate()" value="<?php echo $amount;?>" >
And your Javascript function:
function calculate(){
var sum = 0;
var count = 0;
var a1=document.listForm['payment_id[]'];
for(i=0;i<a1.length;i++){
if (a1[i].checked){
sum += parseInt(a1[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}

Increment textarea name to javascript function

So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}

Categories

Resources