Javascript calcul total in dynamically tab - javascript

I have short problem.
In my form I have multi-input and where the user change the values.
<div id="contenu">
<h2>Renseigner ma fiche de frais du mois <?php echo $numMois."-".$numAnnee ?></h2>
<form method="POST" action="index.php?uc=gererFrais&action=validerMajFraisForfait">
<div class="corpsForm">
<fieldset>
<legend>Eléments forfaitisés
</legend>
<table width=100%>
<tr>
<td>Libelle</td>
<td>Nombre</td>
<td>Montant unitaire</td>
<td>Montant total</td>
</tr>
?>
<tr>
<td width=20%><?php echo $libelle ?></td>
<td width=20%><input type="text" id="<?php echo 'idFrais'.$incr; ?>" name="lesFrais[<?php echo $idFrais?>]" size="10" min="0" autocomplete="off" maxlength="30" value="<?php echo $quantite?>" onkeyup="calculer(this)">
<td width=20%><input type="text" id="<?php echo 'montant'.$incr; ?>" value="<?php echo $montant ?>" disabled></td>
<td id='subtotal<?php echo $incr;?>' width=20%><?php echo $quantite*$montant; ?></td>
</tr>
<?php
$incr ++;
}
?>
<tr>
<td colspan="3">Total : </td>
<td></td>
</tr>
</table>
</fieldset>
</div>
<div class="piedForm">
<p>
<input id="ok" type="submit" value="Valider" size="20" />
<input id="annuler" type="reset" value="Effacer" size="20" />
</p>
</div>
</form>
I want add one line where the total of the col "Montant total" has executed.
Exemple :
And the calcul has been executed direct, no refresh.

First of all instead of using ID for subtotal use Class - subtotal. Then all you have to do is query all of those elements using
querySelectorAll('.subtotal') or $('.subtotal')
and store the resulting array (in jQuery a jQuery object like array) into a variable. Then add events to the quantity input fields and call a function which will iterate over all of the elements in the previously stored array and convert the text stored in them (which was generated using your calculer function) which can be accessed using
subtotal[index].innerText
and parse it into Number using
Number(subtotal[index].innerText)
and check if the resulting number is NaN (Not a Number) or not using isNaN() function. If not add to a local total variable and write the result in the end.
Hope this helps.
Here is the code -
function CalculateTotal(e) {
var subtotal = querySelectorAll('.subtotal');
var subtotalCount = subtotal.length;
var subtotalValue;
var total = 0;
for (var i = 0; i < subtotalCount; i++) {
subtotalValue = Number(subtotal[i].textContent);
if (!isNaN(subtotalValue)) total += subtotal;
}
// Set the total element's textContent here.
}
Call the above function at the end of your calculer function.

Related

Looping through HTML table and store td values as a string using jquery / javascript

I have following table
while($row=mysql_fetch_array($sql))
{
$id=$row['product_id'];
$name=$row['name'];
$stock=$row['stock'];
?>
<tbody>
<tr >
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $name; ?></span>
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php if($stock==0){echo 0;}else{echo $stock;} ?></span>
</td>
<td class="edit_td1" id="<?php echo $id; ?>">
<div class="form-group">
<div class="col-lg-3 inputContainer">
<input class="form-control cls-quantity" id="quanti_<?php echo $id; ?>" name="number" type="text" />
</div>
</div>
</td>
<td class="action_td" id="<?php echo $id; ?>"><span class="glyphicon glyphicon-remove" style="cursor:pointer;color:red;"></span></td>
</tr>
</tbody>
<?php
}
?>
And button:
Generate Bill
Question: Here I want to return a function store_value_as_string(); after td_validation(); which loop through all <tr> and get id of class="edit_td1" and associated value of id="quanti_<?php echo $id; ?>". Then function store_value_as_string(); will gives me two strings
str1 = 121,122,123,124;//id of class="edit_td1"
str2 = 2,3,1,4;//associated value of id="quanti_<?php echo $id; ?>"
these two strings are required for ajax call(pass to other php page).
I actually have code for doing same but it runs onchange of ".edit_td1" but the sequence of operations by -->tester<-- i.e. onchange-blur(leave the textbox for same <tr> -onchange-blure-onchange... gives me wrong output.
Table look likes:
You might wanna use the Jquery each. Iterate over all td's with the class '.edit_td1'. Fetch their id's using .attr('id') and add to an array as well and then later use Jquery's Array join to get your desired output of str1.
For str2 with each loop, find input with the class '.cls-quantity' and get its value. Add that number to a list and then again use Array.join.
I hope my code works fine. Haven't debugged it.
function store_value_as_string(){
var array1= new Array();
var array2 = new Array();
$('td.edit_td1').each(function(index, element){
//Not sure if we need this line.
//Might need if we dont get the element in function's argument
//var element = this;
array1.push($(element).attr('id'));
//find might return an array so can use this line. I have not debugged it.
array2.push($(element).find('input.cls-quantity')[0].val())
//array2.push($(element).find('input.cls-quantity').val());
});
var str1 = array1.join(',');
var str2 = array2.join(',');
}

if loop to get data if present in table if not present then insert value in table and javascript to get the data on writing profile id

I need a if loop in view file and a javascript when profile id is entered it should show all the related elements in the form and i'm doing this in codeignitor and this is the part of view file
<tr>
<td width='50%'>
<table width="50%"><tr>
<td width="50%"><strong>Profile ID </strong></td>
<td width="50%"><input type="text" id="profile_id" name="profile_id" value="<?php echo $reg_personal_details->profile_id;?>"placeholder="Employee ID "/><?php echo form_error('profile_id');?><br></td>
</tr>
<tr>
<td><strong>Employee Name </strong></td>
<td><input type="text" id="profile_fname" name="profile_fname" value="<?php echo $reg_personal_details->profile_fname;?>"placeholder="Employee Name"/><?php echo form_error('profile_fname'); ?><br></td>
</tr>
<tr>
<td><strong>Employee Type </strong></td>
<td>
<input type="text" id="profile_type" name="profile_type" value="<?php echo $reg_personal_details->profile_type;?>"placeholder="Employee Type"/><?php echo form_error('profile_type');?><br>
</td>
</tr>
<tr>
here is my table:
profile
(profile_id,
profile_fname,
profile_lname,
profile_email,
profile_mobile,
profile_type,
profile_gender,
profile_dob,
profile_marital_status,
profile_religion,
profile_blood_group,
profile_nationality,
profile_iris,
profile_biometric,
profile_department,
profile_designation,
profile_project_designation,
profile_image,
address_1,
address_2)
profile_id is a foreign key and its primary key is in other table as emp_acc_id
model for the above is :
public function reg_personal_details()
{
$reg_personal_details = array(
// i also need a condition here to read the entered profile_id all that below data must be store in that id only//
'profile_type' => $this->input->post('profile_type'),
'profile_gender' => $this->input->post('profile_gender'),
'profile_dob' => $this->input->post('profile_dob'),
'profile_marital_status' => $this->input->post('profile_marital_status'),
'profile_religion' => $this->input->post('profile_religion'),
'profile_blood_group' => $this->input->post('profile_blood_group'),
'profile_nationality' => $this->input->post('profile_nationality'),
'profile_iris' => $this->input->post('profile_iris'),
'profile_biometric' => $this->input->post('profile_biometric'),
'profile_department' => $this->input->post('profile_department'),
'profile_designation' => $this->input->post('profile_designation'),
'profile_project_designation' => $this->input->post('profile_project_designation'),
);
$this->db->update('profile',$reg_personal_details);
You Should write a java Script which would check if a particular element exists or not i.e if its value is not null then generate a new row tags dynamically and set its value what we get in response of the query.
For generating a tag dynamically you can refer the following page:-
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
we have a function to check whether data is present or not i.e., empty()and we just need to use it in if loop like this "if (!empty($var name))" and can also use "if(empty($var name)) " so if there is no data then it doesn't show any error and if data is present in db it shows that data
<tr>
<td width='50%'>
<table width="50%"><tr>
<td width="50%"><strong>Profile ID </strong></td>
<td width="50%"><input type="text" id="profile_id" name="profile_id" value="<?php
if (!empty($reg_personal_details)) {
echo $reg_personal_details->profile_id;
} else
echo $profile_id;
?>"placeholder="Employee ID "/><?php echo form_error('profile_id'); ?><br></td>
</tr>
<?php //if($reg_personal_details!=array()){ ?>
<td><strong>Employee Name </strong></td>
<td>
<input type="text" id="profile_fname" name="profile_fname" value="<?php
if (!empty($reg_personal_details)) {
echo $reg_personal_details->profile_fname;
}
?>" placeholder="Employee Name"/><?php echo form_error('profile_fname'); ?><br>
</td>
</tr>
<tr>
<td><strong>Employee Type </strong></td>
<td>
<input type="text" id="profile_type" name="profile_type" value="<?php
if (!empty($reg_personal_details)) {
echo $reg_personal_details->profile_type;
}
?>"placeholder="Employee Type 0/1"/><?php echo form_error('profile_type'); ?><br>
</td>
</tr>
<tr>

how to print textbox value in php

In my code,when any text is entered into the textbox and click on add attribute button, entered value displayed on page for two times, one in first row of table and another one is in first row of second table. Now question is, when i entered text into another textbox which is in second row of second table, it should display the entered text.but it can't display. it is not working.
<script>
var i = 0;
document.getElementById('add-val').innerHTML='';
function insRow()
{
i++;
var x=document.getElementById('myTable').insertRow(-1)
var a=x.insertCell(-1)
var txt=document.getElementById('add-val').value;
a.innerHTML=txt;
// for <tr> of table
var row = document.getElementById("myRow");
var newrow=document.getElementById("myRow1");
var x = row.insertCell(-1);
var y = newrow.insertCell(-1);
x.innerHTML=txt; //+ '<br>' +
y.innerHTML='<input type="text" name="nm" />';
}
document.getElementById('add-val').innerHTML='';
</script>
& this is html code.
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['add'];
echo $val;
}
?>
</form>
It should be
y.innerHTML='<input type="text" name="nm[]" />';
The []'s after nm
name="nm[]"
Serve to store all new generated fields into an array, which can then be accessed by $_POST
Which you then just access like so....
$val = $_POST['nm'];
foreach($val as $v){
echo $v; // display what user entered
}
// var_dump($val) will show you all the users seperate input for each field
HTML Code :
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['nm'];
echo $val;
}
?>
</form>
put the name of input whos value you want to print in place of attr
$val= $_POST['attr'];

How do i get the javascript dynamic row values in php?

jsfiddle
I'm trying to print the input text field values on nextpage (postdata.php). But it always print the first row result only. I didn't get the remaining row values on next page. I've posted my full codes on jsfiddle.. How do i get the remaining js dynamic row values in php (postdata.php page)?
JS
$(document).ready(function(){
$("span").click(function(){
$("#container").append('<tr><td>Email : </td><td><input type="text" name="email[]" placeholder="Email id" /></td> <td>Name : </td><td><input type="text" name="name[]" placeholder="Your Name "/></td> <td><a title="Delete this row" href="javascript:void(0);" class="remove">Del</a></td></tr>');
});
$("#container").on('click','.remove',function(){
$(this).parent().parent().remove();
});
});
Php
<?php
echo "
<table>
<tr>
<td>
Email :
</td>
<td>
$_POST[email]
</td>
<td>
Name :
</td>
<td>
$_POST[name]
</td>
</tr>
</table>";
?>
Since name of fields you declared is array the $_POST becomes multidimensional array.So try like this
<?php
$size = sizeof($_POST['email']);
echo "<table>" ;
for($i=0; $i<$size;$i++)
{
echo "
<tr>
<td>
Email :
</td>
<td>
".$_POST['email'][$i]."
</td>
<td>
Name :
</td>
<td>
".$_POST['name'][$i]."
</td>
</tr>
";
}
echo "</table>";
?>
also in your html change names of Name and Email field to name[] and email[] respectively.Also you have misplaced the form tag. It starts after <table> and ends after <table>. which was not correct. so place form tag before table tag
When you add square brackets to the name of an input field, PHP will receive it's value as an array. Your JS code is fine, but the PHP code doesn't handle arrays at all. Look at the following:
echo "
<table>";
if(!is_array($_POST['email'])) {
$_POST['email'] = array($_POST['email']);
$_POST['name'] = array($_POST['name']);
}
foreach($_POST['email'] as $key => $email) {
// get the corresponding name to the email
$name = $_POST['name'][$key];
echo "<tr>
<td>
Email :
</td>
<td>
$email
</td>
<td>
Name :
</td>
<td>
$name
</td>
</tr>";
}
echo "</table>";
Note: This code will check whether multiple values were submitted or not and will work in both scenarios.

disabled textbox causes errors in PHP page when trying to update table in mysql

I'm caught in a set of twisting codes. I've a table in a form which consists of all the information from one table say emp_info. I am not including all the mysql query and db connection but just suppose this table has fetched information from emp_info table from my database. Example:
<table align="center">
<form name="f1" action="update.php" method="post">
<tr>
<td>Enter name : </td><td><input type="text" name="ename" id="field1"
disabled="disabled" /></td><td><input id="myCheckBox1" type="checkbox"
onclick="enableText1(this.checked, 'field1');" />
</td>
</tr>
<tr>
<td>Enter Address : </td><td><input type="text" name="address" id="field2"
disabled="disabled" /></td><td><input id="myCheckBox2" type="checkbox"
onclick="enableText2(this.checked, 'field2');" /></td>
</tr>
<tr>
<td><input type=""submit value="submit"/></td>
</tr>
</form>
</table>
and following is the respective JAVASCRIPT written in the HEAD section:
<script type="text/javascript">
function enableText1(checkBool, textID)
{
text1 = document.getElementById(textID);
//Disable the text field
text1.disabled = !checkBool;
//Clear value in the text field
if (!checkBool) { text1.value = ''; }
}
function enableText2(checkBool, textID)
{
text2 = document.getElementById(textID);
//Disable the text field
text2.disabled = !checkBool;
//Clear value in the text field
if (!checkBool) { text2.value = ''; }
}
</script>
I want user to check the checkbox to enable the textbox to edit it. What can a user do with it? He can check the checkbox to edit it and when he unchecks it once again textbox will be disabled. That means, what he edited in the checkbox is going to be locked. To prevent him from doing it; I'm setting the textbox to empty; once he unchecks the checkbox. It's working up to it. My real problem starts from here. when the textbox is disabled and he submits the records to update, it throws an error while accepting the value using POST method ($name=$_POST['name']) in update.php:
Notice: Undefined variable: address in C:\xampp\htdocs\xampp\Test\HRMS\try\chcking with checkboxes\update.php on line 4
My main intention is to update the record into the temporary table. When a record is submitted using disabled textbox or empty textbox; in that case I would like to fetch its value from the old table and store it into the temporary table. I do not know how clear I am but accepting some support from enthusiastic master's in coding here. Thanks in advance.
please check my actual code. I am including both the pages below :
<?php
session_start();
if(!$_SESSION['logged'])
{
header("Location: login.php");
exit;
}
echo 'Welcome, '.$_SESSION['user'];
//echo 'Welcome, '.$_SESSION['email'];
//echo 'Welcome, '.$_SESSION['eid'];
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function enableText1(checkBool, textID)
{
text1 = document.getElementById(textID);
//Disable the text field
text1.disabled = !checkBool;
//Clear value in the text field
if (!checkBool) { text1.value = ''; }
}
</script>
</head>
<body>
</body>
</html>
<?php
$user=$_SESSION['user'];
$email=$_SESSION['email'];
$eid=$_SESSION['eid'];
echo "<br>";
//echo $email;
//echo $eid;
//echo $user;
$con = mysql_connect("localhost","mars","mars");
if (! $con)
die(mysql_error());
mysql_select_db("marsweb",$con);
mysql_query(" UPDATE login_info SET user_staus=1 WHERE username='$email'");
$query="SELECT * FROM emp_info WHERE eid='$eid'";
//echo "$query";
$result=mysql_query($query);
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
$userid=mysql_result($result,$i,"eid");
$name=mysql_result($result,$i,"ename");
$password=mysql_result($result,$i,"password");
$address=mysql_result($result,$i,"address");
$source=mysql_result($result,$i,"source");
$salary=mysql_result($result,$i,"salary");
$zip=mysql_result($result,$i,"zip");
$mobile=mysql_result($result,$i,"mobile");
$email=mysql_result($result,$i,"email");
?>
<div class="go_right">
<table width="100" cellpadding="10" cellspacing="0" border="2" align="center">
<form action="change_record1.php" method="post">
<tr>
<td>Employee ID</td><td><input type="text" name="userid" value="<?php echo "$userid" ?>" readonly></td>
</tr>
<tr>
<td>Name:</td><td><input type="text" name="name" value="<?php echo "$name"?>" readonly></td>
</tr>
<!--<tr>
<td>Password: </td><td><input type="text" name="password" value="<?php echo "$password"?>" ></td>
</tr>-->
<tr>
<td>Address:</td><td> <input type="text" name="address" value="<?php echo "$address"?>" id="field1" dissabled="disabled" /></td>
<td><input id="myCheckBox1" type="checkbox" onClick="enableText1(this.checked, 'field1');" /></td>></td>
</tr>
<tr>
<td>Source: </td><td><input type="text" name="source" value="<?php echo "$source"?>"></td>
</tr>
<tr>
<td>Salary: </td><td><input type="text" name="salary" value="<?php echo "$salary"?>" readonly></td>
</tr>
<tr>
<td>Mobile:</td><td> <input type="text" name="mobile" value="<?php echo "$mobile"?>"></td>
</tr>
<tr>
<td>Zip: </td><td><input type="text" name="zip" value="<?php echo "$zip"?>"></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" name="email" value="<?php echo "$email"?>" readonly></td>
</tr>
<tr style="border:#FFF";>
<td><input type="Submit" value="Update"></td>
</tr>
</form>
</table>
<?php
++$i;
}
?>
and the php page which will update the temporary table is given below...
<?php
session_start();
if(!$_SESSION['logged'])
{
header("Location: login.php");
exit;
}
echo 'Welcome, '.$_SESSION['user'];
echo "<br>";
echo "<br>";
?>
<?php
$userid=$_POST['userid'];
//$name=$_POST['name'];
//$password=$_POST['password'];
if(isset($_POST['address']))
$address=$_POST['address'];
$source=$_POST['source'];
$salary=$_POST['salary'];
$mobile=$_POST['mobile'];
$zip=$_POST['zip'];
$email=$_POST['email'];
$con = mysql_connect("localhost","mars","mars");
if (! $con)
die(mysql_error());
mysql_select_db("marsweb",$con);
//echo $userid; echo "<br>";
echo $address; echo "<br>";
if($address=="")
{
$query1="select address from `emp_info` where email='$email'";
$fetched1=mysql_query($query1);
while($record1=mysql_fetch_assoc($fetched1))
{
while(each($fetched1))
{
$address=$record1["address"];
}
}
}
echo $address;
mysql_query("UPDATE temp_emp_info SET eid='$userid' , address='$address' , source='$source' , mobile='$mobile' , zip='$zip' WHERE eid='$userid'");
echo "<br>";echo "<br>";echo "<br>";
echo "<center><h2>Record updated</h2></center><br><br>";
?>
When a field is marked "disabled" it doesn't get submitted to the server, so the value is lost. You either need to adapt your server side code to be aware of the possibility that the textbox is unset, or use readonly="readonly" instead of disabled="disabled" to make the text field uneditable. Read only controls are still submitted to the server, they just can't be edited by the user.

Categories