Jquery sum form inputs in multiple tables - php

I have a PHP page that populates HTML tables from MySQL. It outputs two seperate tables with the IDs 'headTable' and 'visits'. I am trying to sum the values from the 'visit' table and output the sum to the corresponding 'headTable'. There is also a checkbox that populates the input field and I am also having trouble getting the correct sum when checking all of the check boxes. The sum is correct if I manually type in the values. Thanks in advance.
Here is an Example on Fiddle
<table id="headTable">
<tr>
<th>First Table</th>
<th><span id="appliedTotal"></span></th>
</tr>
</table>
<table id="visits">
<tr>
<td>Jane</td>
<td>18.45</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
<tr>
<td>Peter</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
</table>
<table id="headTable">
<tr>
<th>Second Table</th>
<th><span id="appliedTotal"></span></th>
</tr>
</table>
<table id="visits">
<tr>
<td>Ronald</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
<tr>
<td>John</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
</table>
and for my Jquery
<script>
$(document).ready(function(){
$(function() {
$('table input[type="checkbox"]').change(function() {
var input = $(this).closest('td').next('td').find('input');
if ($(this).is(':checked')) {
var amount = $(this).closest('td').prev('td').text();
var sum = 0;
$.each($('table#visits'), function() {
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html('$'+sum.toFixed(2));
});
});
input.val(amount);
} else {
input.val('0.00');
var sum = 0;
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html('$'+sum.toFixed(2));
});
}
});
});
$.each($('table#visits'), function() {
$(".amount").keyup(function() {
var sum = 0;
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html(sum);
});
});
});
});
</script>
This is what I was looking to do.
JSFiddle Example

is it about how to make numbers from dollars? I prefer opposite, but for you case add substring(1) to .val() before passing it to Number()
and a
sum = '$' + sum
before assign to the appliedTotal of course

you can't have two tables or any other tags with the same 'id' at one page.

Related

Dynamically generated form does not recognise different rows

I'm building a dynamically generated table where every row is a form with some inputs and selects and has its own submit.
Here is my code so far:
<script>
$(function () {
$('form').on('submit', function (e) {
var princ = $('#principal').val();
window.princ = princ;
e.preventDefault();
$.ajax({
url: 'post.php',
method: 'GET',
data: {"princ":princ},
success: function (response) {
alert("success");
} }); }); });
</script>
<table id="assets_table">
<thead style=" cursor: pointer;">
<tr style="text-align: left; color: #fff;">
<th>Lender </th>
<th>Principal </th>
<th>Int. % </th>
<th>Term (mo.) </th>
<th>Collateral </th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$competitions_id = $uscom['id'];
$users_query = mysqli_query($con, "SELECT * FROM competitions WHERE competition='$compe'");
$users_query_r = mysqli_fetch_array($users_query);
foreach($users_query as $users_query_r) {
$usn = $users_query_r['Name'];
$usn_query = mysqli_query($con, "SELECT * FROM users WHERE username='$usn'");
$usn_query_r = mysqli_fetch_array($usn_query);
?>
<form>
<tr>
<td> <img src="<?= $punch_query_r['profile_pic'] ?>" alt="user"> <?= $users_query_r['Name'] ?></td>
<td><input id="principal" type="text" value="0" ></td>
<td><input id="rate" type="text" value="0" ></td>
<td><input id="term" class = "term_input" type="text" value="0" ></td>
<td><input id="collateral" type="text" value="0">
<select id="colselect" >
<option selected disabled>Select asset</option>
</select></td>
<td> <input type="submit"></td>
</tr>
<?php
} ?>
</tbody>
</table>
</form>
However I cannot make it work properly because when I click on submit it does not really submit the corresponding row's form but the first one that was submitted.
I've also tried rewritting variables with input paste keyup but it does not solve the problem either because it just gets the last input whch was filled regardless of the row.
Any idea on how to solve it? Many thanks in advance.

How to display Ajax jquery Symfony3.2

I start with ajax with symfony 3.2 and I have a small test sum of the two numbers, the query has been sent well but it does not show, because the status is 200 OK(Inspected google chrome) but does not display. thank you for helping me
this my Controller:
/**
* #Route("/cal",name="cal_page")
*/
public function ajaxAction(Request $request)
{
$num1=$request->query->get('nbr1');
$num2=$request->query->get('nbr2');
$som=$num1+$num2;
var_dump($som);
return $this->render('ProjetBundle:Default:ajax.html.twig',array('som'=>$som));
}
view:
<table>
<tr>
<td>Nombre1</td>
<td><input type="text" name="" id="num1"></td>
</tr>
<tr>
<td>Nombre2</td>
<td><input type="text" name="" id="num2"></td>
</tr>
<tr>
<td>Resultat</td>
<td><span id="resultat"></span></td>
</tr>
<tr>
<td colspan="2"><input type="button" name="" id="bttn" value="somme"></td>
</tr>
</table>
JS:
{% block javascripts %}
<script type="text/javascript">
$(document).ready(function(){
$( "#bttn" ).click(function(e) {
e.preventDefault();
var nbr1 = $('#num1').val();
var nbr2 = $('#num2').val();
if (isNaN(nbr1)|| isNaN(nbr2)) {
alert('nbr1 ou nbr2 number');
}
else{
$.ajax({
type:'GET',
data:{nbr1:nbr1,nbr2:nbr2},
url:'{{path('cal_page')}}',
success:function(data){
$('#resultat').html(data);
console.log('aiza ah');
}
});
}
});
});
</script>
{%endblock%}
Maybe it's at the twig level that there is something that does work, thank in advance for your help
You have to actually tell your twig template to show your answer, it won't just magically appear.
For example, to place it in your element with id resultant, you could do the following. The |default filter will take care of the case where som variable is empty.
<table>
<tr>
<td>Nombre1</td>
<td><input type="text" name="" id="num1"></td>
</tr>
<tr>
<td>Nombre2</td>
<td><input type="text" name="" id="num2"></td>
</tr>
<tr>
<td>Resultat</td>
<td><span id="resultat">{{ som|default }}</span></td>
</tr>
<tr>
<td colspan="2"><input type="button" name="" id="bttn" value="somme"></td>
</tr>
</table>

Need HTML Form to Submit Multiple Rows into SQL Database

So I just got done with figuring out some javascript issues with my form in this topic: How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?
But since I had such a multi-part question I have been asked to create a new topic. Below is my new code that I am using where I am stuck and wanting to be able to submit my form, which has the capability if adding multiple rows, to my database and add those HTML rows to rows in the SQL database, respectively.
PREVIEW: http://cl.ly/image/0K0Z202O1Q3e/Screen%20Shot%202013-03-14%20at%203.00.19%20PM.png
HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city" name="co_city">
<input type="hidden" id="co_state" name="co_state">
<input type="hidden" id="co_zipcode" name="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name" name="company_name" /></select></td>
<td><input name="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup();" /></td>
<td><input id="co_lat" name="co_lat" type="text" /></td>
<td><input id="co_long" name="co_long" type="text" /></td>
<td><input id="co_address" name="co_address" type="text" /></td>
</tr>
</table>
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button onclick="deleteRow(); return false;">Delete Row</button>
<button id="ActionSubmit">Submit</button>
</body>
</html>
scripts.js
//Button Functions
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
values[this.name] = this.value;
});
return values;
}).get();
$.post('./php/upload_survey.php', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("Thank you. Your form has been submitted.");
console.log(response);
});
});
});
//Delete Selected Rows
function deleteRow() {
try {
var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 3) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e) {
alert(e);
}
};
upload_survey.php
//Assign passed parameters
$values = json_decode($_POST['json']);
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$sql="INSERT INTO table_name (company_name,...,...)
VALUES ($values)";
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
**So far every time I try to get this working the JS fires successfully, but I get an error in Chrome's Developer Toolbox: Unable to Make Query:Column count doesn't match value count at row 1
This refers to this function in js file: console.log(response);
I think there is no such thing as batch inserts in PHP. There is no equivalent for JAVA's addBatch & executeBatch.
So the right way to do it is simply iteratation over array and insert single row with prepared statement.

How To Input Data from dynamic number of fields in html form

this code is to create dynamic number of fields and to send data.. this is doing it's work...
but then i try to back.php(where form sends the data ) i don't know hoe to get the exact number of rows... id = 0_1 .... 3_1 there are many options.. but what is the exact number to counting to make a loop...
please help me on this asap ...
<html>
<head>
<title>Infinite Form Rows</title>
<script
type="text/javascript"
src="http://cachefile.net/scripts/jquery/1.2.3/jquery-1.2.3.min.js">
</script>
<script type="text/javascript">
$(function(){
var newRowNum = 0;
$('#addnew').click(function(){
newRowNum += 1;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html(newRowNum);
$('input', newRow).each(function(i){
var newID = newRowNum + '_' + i;
$(this).attr('id',newID).attr('name',newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
return false;
});
return false;
});
});
</script>
</head>
<body>
<form action="back.php" method="get" >
<table id="tabdata">
<thead>
<tr>
<th>Row</th>
<th>Cell 1</th>
<th>Cell 2</th>
<th>Cell 3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td><input id="n0_1" name="n0_1" type="text" /></td>
<td><input id="n0_2" name="n0_2" type="text" /></td>
<td><input id="n0_3" name="n0_3" type="text" /></td>
<td></td>
</tr>
<tr>
</tr>
</tbody>
</table>
<input id="go" name="go" type="submit" value=" Save " />
</form>
</body>
</html>
You can maintain a hidden input that contains the current number of rows. Set the value on the click event handler for #go.
$('#go').click(function() {
var numRows =$('#tabdata tbody tr').length;
$('#myHiddenInput').val(numRows);
});

Placement issues in adding input rows dynamically using jQuery

Here is the script to add dynamic rows. It works completely fine with only one error. When I click on Add link, it adds the new row. However, the initial row (only select input tag) comes below, and the new row while other remains at there only :(
Please see the HTML code, also below.
Please see this image for more description:
<script type="text/javascript" src="http://cachefile.net/scripts/jquery/1.2.3/jquery-1.2.3.min.js"></script>
<script type="text/javascript">
$(function(){ var newRowNum = 0;
$('#addnew').click(function(){
newRowNum += 1;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html(newRowNum);
$(':input', newRow).each(function(i){
var newID = newRowNum + '_' + i;
$(this).attr('id',newID).attr('name',newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
newRowNum -= 1;
return false;
});
$('#go').click(function(){
var numRows=$('#tabdata tbody tr').length;
$('#myHiddenInput').val(numRows);
});
return false; }); });
</script>
Here is the HTML part
<form action="issue-item.php" method="POST">
<fieldset style="width: 1714px;">
<legend style="font-family: fantasy; font-style: !important; color: teal; font-size:30px ;">Issue</legend><br /><br />
<table id="tabdata" align="left" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<td>S.No.</td>
<td align="center">Date</td>
<td align="center">Name of Person</td>
<td align="center">Name Of Item</td>
<td align="center">Quantity</td>
<td align="center">Purpose</td>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td><input type="text" name="0_0" style="width: 120px;"/></td>
<td><input type="text" name="0_1" style="width: 170px;"/></td>
<td>
<select name="0_2" size="1">
<option>Choose item</option>
<?php
require('blogic.php');
$obj = new blogic();
$result = $obj->select("select id,name_item from store_item");
$count=$obj->select("SELECT COUNT(*) FROM store_item");
$obj->rows = mysql_num_rows($count);
while($objres = mysql_fetch_row($result))
{
$str=<<<here
<option value="$objres[0]">$objres[1]</option>
here;
echo $str;
}
?>
</select>
</td>
<td><input type="text" name="0_3" style="width: 80px;"/></td>
<td><input type="text" name="0_4" style="width: 280px;"/></td>
</tr>
<tr>
<td>
<input type="hidden" id="myHiddenInput" name="myHiddenInput" value="1"/>
</td>
</tr>
<tr><td><input id="go" name="go" type="submit" /></td></tr>
</tbody>
</table>
</fieldset>
</form>
Add following lines after $('input', addRow).val('');:
$('select', newRow).val($('select', addRow).val());
$('select', addRow).val('');
Also see my example.
=== UPDATE ===
Or replace $('input', addRow).val(''); with:
$('select', newRow).val($('select', addRow).val());
$(':input', addRow).val('');
Also see my updated example.

Categories