How to calculate from each row data textbox value in array? - javascript

I want to show total sum of values for each row data array. I have 5 rows of data, I want to get the results of each of data. Can anyone help me to figure it out?
function subtotal(konversi){
var hitung = (document.getElementById('quantity').value * document.getElementById('packing_value').value);
document.forms.demoform.quantity_konversi.value = hitung;
}
<form id='demoform'>
<?php
$jumlah=5;
for($i=0; $i<$jumlah; $i++){
$nomor = $i + 1;
echo"$nomor";
?>
<input type='text' name='quantity[]' id='quantity' onchange="subtotal(this.value,getElementById('packing_value').value);">
X
<input type='text' id="packing_value" value='10' readonly='yes'>
<input type='text' name='quantity_konversi[]' id='quantity_konversi' placeholder='result ???'><br/>
<?php } $nomor++ ?>
</form>

Your problem is that all the input fields have the same id. In HTML every element/html tag should have a unique id. So if you reference with the id JavaScript will find the first occurence of your id and use this element. All other elements are ignored even though they have the same id.
So remember ids are unique, classes can be used on several elements.
To solve your problem I added an unique ID at the end of the regular quantity id with the PHP variable $nomor:
<input type='text' name='quantity[]' id='quantity<?php echo"$nomor"; ?>' onkeyup="subtotal();">
The PHP server will make the following out of it:
<input type='text' name='quantity[]' id='quantity1' onkeyup="subtotal();">
<input type='text' name='quantity[]' id='quantity2' onkeyup="subtotal();">
...
<input type='text' name='quantity[]' id='quantity5' onkeyup="subtotal();">
You know have a unique id that can be referenced by JavaScript with the help of a running index inside of a for loop:
document.getElementById('quantity'+i).value
The same goes for document.getElementById('packing_value'+i).value
Finally the calculated value is saved in the correct field:
document.getElementById('quantity_konversi'+i).value = hitung;
FULL CODE (runnable at http://phpfiddle.org/):
<script>
function subtotal(konversi){
console.log('subtotal function');
for(var i = 1; i < 5+1; i++){
//console.log('quantity'+i, document.getElementById('quantity'+i).value);
//console.log('packing_value'+i, document.getElementById('packing_value'+i).value);
var hitung = (document.getElementById('quantity'+i).value * document.getElementById('packing_value'+i).value);
//document.forms.demoform.quantity_konversi.value = hitung;
document.getElementById('quantity_konversi'+i).value = hitung;
console.log(i, hitung);
}
}
</script>
<form id='demoform'>
<?php
$jumlah=5;
for($i=0; $i<$jumlah; $i++){
$nomor = $i + 1;
echo"$nomor";
?>
<input type='text' name='quantity[]' id='quantity<?php echo"$nomor"; ?>' onkeyup="subtotal();">
X
<input type='text' id="packing_value<?php echo"$nomor"; ?>" value='10' onkeyup="subtotal();">
<input type='text' name='quantity_konversi[]' id='quantity_konversi<?php echo"$nomor"; ?>' placeholder='result ???'><br/>
<?php
} //for end
$nomor++
?>
</form>

Related

How can put my values to mysql from my php table with jquery ajax method

<div id="kutu">
<?php
echo "<table ' border='1' width='200px'>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Oyuncu Adi</th>";
echo "</tr>";
for ($x = 1; $x <= $playernum; $x++) {
echo "<tr>";
echo "<td>$x </td>";
echo "<td><input id='serdar' type='text' name='player$x' > </td>";
echo "</tr>";
}
echo "</table>";
?>
<p> <input type="submit" value="Kayit Et!"></p>
</div>
Im taking $playernum from other page. In this table I will take players name and I wanna put this names to my mysql db with javascript ajax method. But I couldnt find the way.
My table looks like:
I suggest you change your input-text to the same name like this, instead of player$x:
<form method="POST">
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" />
<p id="result"></p>
<button id="btn">Get Player Names</button>
</form>
For the javascript:
<script>
$("form").submit(function(e) {
e.preventDefault();
players = document.getElementsByName("player");
var result = [];
for (var i = 0; i < players.length; i++) {
result[i] = players[i].value;
}
$.post(
'index.php', {
data: result
},
function(msg) {
document.getElementById("result").innerHTML = msg;
}
);
});
</script>
I just created an empty array and stored the values of each input into it. Then sent that array over to the PHP file.
For the index.php file:
$data = $_POST["data"];
echo "From PHP<br/>";
foreach ($data as $d){
echo $d . "<br/>";
}
So you can use the variable $d to access individual player names.
Result image

How do you assign variables or work with numbers in forms created by php loops?

I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>

Javascript Add New Input Field in Increasing Order

I'm having trouble getting my javascript to add a variable to getElementById. What I'm doing is allowing the users to have 10 authors per post. The script shows the authors already entered in the system and now I'm trying to allow them to add more input fields only to the point that 10 fields show up. Here is the code I have so far:
$y=1;
//GET EXISTING AUTHORS FOR POST
while ($getauthorsrow=$getauthorssql->fetch()) {
$showauthor = $getauthorsrow['author'];
$authorid = $getauthorsrow['ID'];
echo "<input type='text' value='$showauthor' name='authorname[]'>
<input type='hidden' value='$authorid' name='authorid[]'><br><br>";
$y++;
}
$newy=$y-1;
?>
//SCRIPT TO ADD NEW FIELD ONLY TO THE POINT OF 10
<script language="javascript">
fields = <?php echo $newy; ?>;
function addInput<?php echo $i; ?>() {
if (fields != 10) {
//HERE I'M TELLING IT TO GET text + $i (which is post number) + fields variable
//So if it's the first post and the new field divs start a 5
//Then it should getElementByid('text05') and continue on.
document.getElementById('text<?php echo $i; ?>' + fields).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById('text<?php echo $i; ?>' + fields).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform<?php echo $i; ?>.add<?php echo $i; ?>.disabled=true;
}
}
</script>
//HERE I'M ADDING THE NEW DIVS FOR TEXT FIELDS AND STARTING
//THEM AT WHATEVER NUMBER POST $i IT IS AND WHATEVER THE $w is.
//SO IN THE EXAMPLE IN THE JAVASCRIPT IT'D SAY id='text05'
//THIS WORKS JUST FINE
<?php
$w=$newy;
while ($w<=10) {
echo "<div id='text".$i.$w."'></div>";
$w++;;
}
//ECHO THE ADD AUTHOR BUTTON
echo "
<input type='button' onclick='addInput$i()' name='add$i' value='Add Author'><br>
<input type='hidden' name='count' value='$newy'>
<input type='hidden' name='id' value='$fileid'>
<input type='submit'>
</form>
";
?>
$i is the post number starting from 0. The php to make the divs works fine. I'm just getting null for the getElementById in the javascript. What am I getting wrong here?
HTML Output Example:
<form id="ajaxform0">
<input type="text" value="Logan" name="authorname[]">
<input type="hidden" value="121" name="authorid[]"><br><br><input type="text" value="Matt" name="authorname[]">
<input type="hidden" value="122" name="authorid[]"><br><br><input type="text" value="Chad" name="authorname[]">
<input type="hidden" value="123" name="authorid[]"><br><br><input type="text" value="hey" name="authorname[]">
<input type="hidden" value="128" name="authorid[]"><br><br><input type="text" value="jordan" name="authorname[]">
<input type="hidden" value="129" name="authorid[]"><br><br>
<script language="javascript">
fields = 5;
function addInput0() {
if (fields != 10) {
var currentText = 'text0' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById(currentText).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform0.add0.disabled=true;
}
}
</script>
<div id="text05"></div><div id="text06"></div><div id="text07"></div><div id="text08"></div><div id="text09"></div><div id="text010"></div>
<input type="button" onclick="addInput0()" name="add0" value="Add Author"><br>
<input type="hidden" name="count" value="5">
<input type="hidden" name="id" value="45">
<input type="submit">
</form>
Try assigning that concatenated string to a JS variable first, then calling the function:
if (fields != 10) {
var currentText = 'text<?php echo $i; ?>' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById(currentText).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform<?php echo $i; ?>.add<?php echo $i; ?>.disabled=true;
}
I need to add the $i to the fields variable in the javascript. With multiple files it was doing multiples of the same variable...i works.
Hi I have modified your code for html and JavaScript.
<form id="ajaxform0">
<input type="text" value="Logan" name="authorname[]">
<input type="hidden" value="121" name="authorid[]"><br><br><input type="text" value="Matt" name="authorname[]">
<input type="hidden" value="122" name="authorid[]"><br><br><input type="text" value="Chad" name="authorname[]">
<input type="hidden" value="123" name="authorid[]"><br><br><input type="text" value="hey" name="authorname[]">
<input type="hidden" value="128" name="authorid[]"><br><br><input type="text" value="jordan" name="authorname[]">
<input type="hidden" value="129" name="authorid[]"><br><br>
<script language="javascript">
fields = 5;
function addInput0() {
if (fields != 10) {
var currentText = 'text0' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
var myout = "Only 10 authors allowed.";
document.getElementById("stat").innerHTML = myout;
}
}
</script>
<div id="text05"></div><div id="text06"></div><div id="text07"></div><div id="text08"></div><div id="text09"></div><div id="text010"></div><div id="stat"></div>
<input type="button" onclick="addInput0()" name="add0" value="Add Author"><br>
<input type="hidden" name="count" value="5">
<input type="hidden" name="id" value="45">
<input type="submit">
Check it and let me know, if it is solved.

Calculation using JS not showing

I am trying to build a web app in php something like stock maintenance, in my earlier page the user is allowed to insert the values of the bill which he gets from the dealer, as in from whom he buys the items which he sells from his shop, hence there he inserts details about the products bought, quantity, price per pc and the rest, i mean total price and the grand total is calculated using JS.
now there is another page where the user sets his profit percent on the grand total(Grand total= total price of the products + Transportation price) and i want the selling price of each item to calculated on its own, using a button.
the rest details are being fetched from the database.
the user sets the profit% on the grand total and now i have used the JS to calculate for each item.
<script type="text/javascript">
function poffy()
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice").value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant").value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice").value=h;
}
}
</script>
Now The problem is that the calculated value is being displayed only once and only for the first item ,not for the other rows.
My php code:
<?php
include("connect.php");
$wer='ccat';
$i=0;
$dater=date("D/M/Y");
$sq="SELECT D_id FROM dealerdetail where Dealer='$wer'";
$res=mysql_query($sq);
while($row=mysql_fetch_array($res))
{
$did=$row["D_id"];
}
$io="Select pdate,tranprice,grandtotal from dateprice where D_id='$did'";
$qw=mysql_query($io);
while($row=mysql_fetch_array($qw))
{
$pd=$row["pdate"];
$as=$row["tranprice"];
$as=0 + $as;
$tr=$row["grandtotal"];
$tr=0 + $tr;
$sql="Select * from additem where Ditem_id='$did'";
$result = mysql_query($sql);
while($pop=mysql_fetch_array($result))
{
$b= $pop["Product"];
$c= $pop["Brand"];
$d= $pop["Model"];
$e= $pop["Dprice"];
$f= $pop["Quantity"];
$t=$e*$f;
$g= $pop["Quality"];
echo "<tr>";
echo "<td> $wer</td>";
echo "<td> $b </td>";
echo "<td> $c </td>";
echo "<td> $d </td>";
echo "<td><input type=text name=costprice id=costprice onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice /></td>" ;
echo "<td> <div align=center ><p>$g<p></div> </td>";
/*echo "<td><input type=text name=purchasedt value=$pd /></td> "; */
echo "<td><input type=text name=current value=$dater /></td>
</tr>";
$i++;
/* if(isset($_POST['S.P']))
{
$po=$_POST['grandy'];
$ap=$po-$tr;
$ao=$ap/$i;
$ai=$ao/$f;
$ul=$_POST['costprice'];
$re=$ai + $ul;
echo $re;
}
*/
}
}
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
?>
</table>
<?php
echo "<br><br><label> Transport Price :</label><input type = text name=transport value=$as > <br>";
echo " <br><label> Grand Total : </label> <input type = text name=grandy id=grt value=$tr > ";
?>
<br >
<br >
<input type="button" name="proft" onclick="calcu();" value="Profit" />
<input type ="text" name="grandy" id="ui" />
I see you already have a variable $i that you're incrementing on every row, you can use that to make the IDs unique:
echo "<td><input type=text name=costprice id=costprice$i onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant$i value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice$i /></td>" ;
Then change your Javascript to take a parameter that specifies the row:
function poffy(i)
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice"+i).value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant"+i).value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice"+i).value=h;
}
}
I don't see where in your HTML you call the poffy() function. You need to change that code to pass the row number as a parameter.
I noticed another problem in your code. You have the following at the bottom of the table:
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
Everything in a <table> has to be inside <tr> and <td> or <th> elements. You either need to put those wrappers around this line, or move them out of the table.

Php, get the values from a text box to the next page

I am relatively new to PHP Mysql, I am struck on this problem, My problem is I have a from with two textboxes (name, sal) and i got the values from mysql. Now I am making changes in the sal text box, i am making some changes int he form textboxes, I want to see the vlaues from this form which are changed or unchanged to another form. How to do it.
I am getting the Last row only as result not all the values from the text boses.
The code is
File Name: emp.php
<form name = "emp.php" action = "emp_new.php" >
<?php
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result))
{
$emp_name = $row["emp_name"];
$emp_sal = $row["emp_sal"];
echo "<input type='Text' name='$emp_name' value= '$emp_name' size='8' id='emp_name'>";
echo "<input type='Text' name='emp_sal' value= '$emp_sal' size='8' id='emp_sal'>";
}
<input type=submit name="process" value="Process">
Clicking on the process i want to display all the content in the text boxes in page
emp_new.php
use array element on the form like emp_name[]
<form name = "emp.php" action = "emp_new.php" method="post" >
<?php
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array($result))
{
$emp_name = $row["emp_name"];
$emp_sal = $row["emp_sal"];
echo "<input type='Text' name='emp_name[]' value= '$emp_name' size='8' id='emp_name'>";
echo "<input type='Text' name='emp_sal[]' value= '$emp_sal' size='8' id='emp_sal'>";
}
<input type="submit" name="process" value="Process">
on emp_new.php do the following
$emp_name=$_POST['emp_name'];
$emp_sal=$_POST['emp_sal'];
foreach($emp_name as $key=>$val){
$name=$val;
$sal=$emp_sal[$key];
}
just name the text boxex distinctly.. assuming that you have list of less than 100 employees.
<form method="post" action = "emp_new.php" >
<?php
$result = mysql_query("SELECT * FROM emp");
$name=1;
$sal=100;
while($row = mysql_fetch_array($result))
{
$emp_name = $row["emp_name"];
$emp_sal = $row["emp_sal"];
echo "<input type='Text' name='$name++' value= '$emp_name' size='8' id='emp_name'/>";
echo "<input type='Text' name='$sal++' value= '$emp_sal' size='8' id='emp_sal'/>";
}
echo "<input type='hidden' value=$name name='size' />";
?>
<input type=submit name="process" value="Process">
To access these value in new fom is use following code
in new_emp.php
<?php
$name=1;
$sal=100;
for($i=1;$i<=$size;$i++)
{
$emp_name = $_post[$name];
$emp_sal = $row["$sal];
echo "<input type='Text' name='$name++' value= '$emp_name' size='8' id='emp_name'>";
echo "<input type='Text' name='$sal++' value= '$emp_sal' size='8' id='emp_sal'>";
}
?>

Categories