I am working with DreamWeaver, PHP, MySQL, JQuery Mobile and JavaScript. I am showing MySQL records on a table and each row has an edit link to open an update record file. Using JavaScript in an insert record file, I am able to calculate fields values using a JavaScript function, but now, I am trying to do the same in an update record file.
The problem I have now, is that on the second file the JavaScript function is called, but any calculation is made.
The only difference I see there is that on the second file (update record) the fields already have a value, but I am not sure if that is the source of the problem, but I guess not, then the user can manually change the values.
This is the JavaScript code for both files:
<script type="text/javascript">
function calculatetotal(){
alert("I am an alert box!");
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
var totaliva =0;
var totcliente =0;
totcliente = (mat+mo+uti+ind).toFixed(2);;
var totaliva = ((poriva)/100)*totcliente;
document.getElementById('totCliente').value = (mat+mo+uti+ind).toFixed(2);
document.getElementById('totaliva').value = totaliva;
document.getElementById('totalpre').value= parseFloat(totaliva)+parseFloat(totcliente);
}
</script>
I need your help to understand why is it working on the insert record file and not on the update record file.
This is the code for the form part in HTML from the update record part:
<form method="post" name="form1" id="form1" data-ajax="false" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Obra:</td>
<td><select name="int_obra">
<?php
do {
?>
<option value="<?php echo $row_Recordset2['idObra']?>" <?php if (!(strcmp($row_Recordset2['idObra'], htmlentities($row_Recordset1['int_obra'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>><?php echo $row_Recordset2['nombreObra']?></option>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
?>
</select></td>
<tr>
<tr valign="baseline">
<td nowrap align="right">Materiales:</td>
<td><input type="text" name="dbl_materiales" value="<?php echo htmlentities($row_Recordset1['dbl_materiales'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="mat" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Mano de Obra:</td>
<td><input type="text" name="dbl_mano_de_obra" value="<?php echo htmlentities($row_Recordset1['dbl_mano_de_obra'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="mo" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Utilidad:</td>
<td><input type="text" name="dbl_utilidad" value="<?php echo htmlentities($row_Recordset1['dbl_utilidad'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="uti" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Indirectos:</td>
<td><input type="text" name="dbl_indirectos" value="<?php echo htmlentities($row_Recordset1['dbl_indirectos'], ENT_COMPAT, 'UTF-8'); ?>" id="ind" onChange="calculatetotal()"size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Pre. aprobado por cliente:</td>
<td><input name="dbl_total" type="text" id="totcliente" value="<?php echo htmlentities($row_Recordset1['dbl_total'], ENT_COMPAT, 'UTF-8'); ?>" size="32" readonly></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">% IVA:</td>
<td><input type="text" name="dbl_porcentaje_iva" value="<?php echo htmlentities($row_Recordset1['dbl_porcentaje_iva'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="poriva" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Total IVA:</td>
<td><input name="dbl_total_iva" type="text" value="<?php echo htmlentities($row_Recordset1['dbl_total_iva'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="totaliva" readonly></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">TOTAL DEL PRESUPUESTO:</td>
<td><strong>
<input name="dbl_total_presupuesto" type="text" value="<?php echo htmlentities($row_Recordset1['dbl_total_presupuesto'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="totalpre" readonly>
</strong></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">MONEDA:</td>
<td><select name="int_moneda">
<option value="1" <?php if (!(strcmp(1, htmlentities($row_Recordset1['int_moneda'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>>PESO MXN</option>
<option value="2" <?php if (!(strcmp(2, htmlentities($row_Recordset1['int_moneda'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>>USD</option>
</select></td>
</tr>
<tr valign="baseline">
<td nowrap align="right"> </td>
<td><input type="submit" value="Actualizar Presupuesto"></td>
</tr>
</table>
<input type="hidden" name="MM_update" value="form1">
<input type="hidden" name="idPresupuesto" value="<?php echo $row_Recordset1['idPresupuesto']; ?>">
</form>
I have updated the JavaScript code, and now it works as expected. Thank you for your help.
<script type="text/javascript">
function calculatetotal(){
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
totcliente = (mat+mo+uti+ind).toFixed(2);
var totaliva = parseFloat(((poriva)/100)*totcliente);
document.getElementById('totcliente').value = totcliente;
document.getElementById('totaliva').value = totaliva.toFixed(2);
document.getElementById('totalpre').value = (parseFloat(totcliente)+parseFloat(totaliva)).toFixed(2);
}
</script>
add your script a the end of the page juste before </body> and call the function :
<script type="text/javascript">
function calculatetotal(){
alert("I am an alert box!");
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
var totaliva =0;
var totcliente =0;
totcliente = (mat+mo+uti+ind).toFixed(2);;
var totaliva = ((poriva)/100)*totcliente;
document.getElementById('totCliente').value = (mat+mo+uti+ind).toFixed(2);
document.getElementById('totaliva').value = totaliva;
document.getElementById('totalpre').value= parseFloat(totaliva)+parseFloat(totcliente);
}
calculatetotal();
</script>
</body>
</html>
Related
In this problem, when I sum a number to the quantity with the button,I want to change the total but it doesnt change, which is this line:
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
Here's the php code
<tr>
<td width="40%"><?php echo $producto['NOMBRE'] ?></td>
<td><button onclick="add_number()">mas</button><input type="text" id="suma" name="suma" value="<?php echo $producto['CANTIDAD'] ?>" readonly="readonly"></input></td>
<td width="20%" class="Text-center"><?php echo $producto['PRECIO'] ?></td>
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
<td width="5%">
<form action="" method="post">
<input type="hidden"
name="id"
value="<?php echo openssl_encrypt($producto['ID'],COD,KEY); ?>">
<button
class="btn btn-danger"
type="submit"
name="btnAccion"
value="Eliminar"
>Eliminar</button>
</form>
</td>
</tr>
Here's the Java code:
function add_number() {
var first_number = parseInt(document.getElementById("suma").value);
var result = first_number + 1;
document.getElementById("suma").value = result
}
In the function add_number where you increment the quantity value, you can also add the price to total cell of table each time, change your JavaScript function like this:
function add_number() {
var suma = parseInt(document.getElementById("suma").value); /* get current quantity */
var total = parseInt(document.getElementById("total").innerHTML); /* get current total */
var percio = parseInt(document.getElementById("percio").innerHTML); /* get price */
document.getElementById("suma").value = suma + 1; /* change quantity */
document.getElementById("total").innerHTML = (suma + percio).toFixed(2); /* change total */
}
Note the usage of innerHTML and value. The difference is because value is used for <input> tag while innerHTML is used for <td> tag.
Also note that you need to sed id for total cell and price cell in oder to read and write in them in your JavaScript function.
<td width="20%" class="Text-center" id="percio">
<?php echo $producto['PRECIO'] ?>
</td>
<td width="20%" class="Text-center" id="total">
<?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?>
</td>
I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.
What is the issue i cannot understand. I have tried by moving code in the java but no use.
Suppose i have 2 items.
Item1 total is = 100
Item2 total is = 200
Total should be 300 not only the 1 items total.
Below is my code.
Thanks in advance
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<table class="table mg-bottom-45 refresh" id="myTable">
<thead>
<tr>
<th class="product-cart-price"><span>PRICE</span></th>
<th class="product-cart-price"><span>TOTAL</span></th>
</tr>
</thead>
<tbody>
<?php
include ('inc/db.php');
$citem = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
$userID = $cifetch['user_id'];
?>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="<?php echo $cifetch['price']; ?>"
value="<?php echo $cifetch['price']; ?>" class="un pricex" />
</td>
<?php } ?>
<td class="totalAmount"></td>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = '';
$('#myTable > tbody > tr').each(function() {
var quantityx = $(this).find('.quant').val();
var pricex = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantityx * pricex).toFixed(3);
sumx += amountx;
});
$('.totalAmount').text(sumx);
}
});
</script>
First, please make sure that your loop is running multiple times (same number of products in cart).
$('#myTable > tbody > tr').each(function() {})
so that the above loop iterate exact number times as per required.
You should make some changes in code as follows:
var sumx = 0.00;
and in loop code should be
sumx += parsefloat(amountx);
So here is the solution with some changes in my code.
Now it is working perfectly as required. It is doing the sum of all items and everything what i want.
<table class="table mg-bottom-45 refresh" id="myTable">
<tbody>
<?php
$i = 0;
//error_reporting(0);
$ses_mem = 1;
include ('inc/db.php');
$citem = "select id, user_id, qty, org_price from orders_temp
where user_id = '".$ses_mem."' and status = 1
order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
?>
<tr>
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = 0.000;
var quantity;
$('#myTable > tbody > tr').each(function() {
quantity = $(this).find('.quant').val();
var price = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantity * price);
var munterx = amountx.toFixed(3);
sumx += amountx;
$(this).find('.amountx<?php echo $orderID; ?>').text('' + munterx);
});
var sumxx = sumx.toFixed(3);
$('.total').text(sumxx);
}
});
</script>
<td class="single-qty" style="border: 0;">
<input id="<?php echo $orderID; ?>" name="quantity" type="text"
data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-price pricex" data-price="<?php echo $cifetch['org_price']; ?>">
</td>
<td class="amountx<?php echo $orderID; ?>">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="table">
<tbody>
<tr>
<td>Sub Total (RS)</td>
<td class="text-right"
style="text-shadow: 2px 2px 3px #999999; font-weight: bold;
color: black; direction: rtl;">
<span class="total">
</span>
</td>
</tr>
</tbody>
</table>
this is my controller file
below code is working only file uploading into path and no data is displaying in database when i gave inputs. Another doubt, It is not showing validation errors when i submit with empty inputs.
var $default_news_status = 1;
var $default_client_status = 1;
var $default_client_partner_flag = 0;
var $default_client_logo_display_flag = 1;
var $default_client_test_status = 0;
public function construct()
{
parent::__construct();
$this->load->helper(array('form', 'url', 'file'));
}
/*controlles vadmin/addnews*/
public function addnews()
{
//$status = "";
//$msg = "";
$userfile = 'userfile';
//echo '<br>entered into ajax if block.. ';
/******* extracting file extension ********/
$org_filename = $_FILES['userfile']['name'];
$path_parts = pathinfo($org_filename);
//$file_extension = $path_parts['extension'];
/***** end extracting file extension ******/
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[5]');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('url', 'URL', 'trim|required');
$this->form_validation->set_rules('userfile', 'Image', 'trim');
$this->form_validation->set_rules('postedon', 'Posted On', 'trim|required');
$this->form_validation->set_rules('source', 'Source','trim|required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('expiredate', 'Expire Date', 'trim|required');
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 1000;
//$config['file_name'] = 'client_'.time().'.'.$file_extension;
//echo "<pre>";
//print_r($_FILES);
$this->load->library('upload', $config);
if (!$this->upload->do_upload($userfile))
{
echo '<br>entered into upload failed block.. ';
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
echo '<br>entered into upload success block.. ';
/*$data = $this->upload->data();
echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $this->input->post('userfile');
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
/**** end assignment of post data ******/
/**** load news model to insert reocrd into table *****/
$this->load->model('vadmin/Newsmodel','',true);
$this->Newsmodel->addRequestForm();
/**** load news model to insert reocrd into table *****/
//print jsone response for ajax request
echo json_encode(array('status'=>0, 'msg' => 'Successfully Submitted'));
}
}
here is my view form
and js file is given below
<form method="post" action="" name="newsform" id="newsform" enctype= "multipart/form-data" >
<input type="hidden" value="" id="id" name="id" required="true">
<table width="580" cellpadding="5" cellspacing="5">
<tr>
<td width="130" align="left"><span class="required">*</span>Title</td>
<td align="left"><input name="title" type="text" id="title" style="width:250px;" value="<?php echo $news_title; ?>"/></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Description</td>
<td align="left"><textarea name="description" rows="8" cols="40" id="description" style="width:250px;" ><?php echo $news_description; ?></textarea></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>URL</td>
<td align="left"><input name="url" type="text" id="url" style="width:250px;" value="<?php echo $news_url; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Image</td>
<td align="left"><input name="userfile" type="file" id="userfile" style="width:250px;" value="<?php echo $news_image; ?>" /></td>
<tr>
<td width="130" align="left"><span class="required">*</span>Posted On</td>
<td align="left"><input name="postedon" id="datepicker" style="width:250px;" value="<?php echo $news_posted_on; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Source</td>
<td align="left"><input name="source" type="text" id="source" style="width:250px;" value="<?php echo $news_source; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Expire Date</td>
<td align="left"><input name="expiredate" id="datepicker1" style="width:250px;" value="<?php echo $news_expire_date; ?>"/></td>
</tr>
<td colspan="2" align="left"><input type="submit" value="Submit" id="submit" onclick="return ajaxFileUpload();" />
<input type="reset" value ="reset" id="reset" /><span id="loading" >Please wait ..</span></td>
</tr>
</table>
<input type="hidden" name="nid" id="nid" value="<?php echo $news_id; ?>" />
</form>
here is my script
$.ajaxFileUpload
(
{
url:'<?php echo base_url();?>vadmin/ajax/addnews/',
secureuri:false,
fileElementId:'userfile',
dataType: 'json',
data: $("#newsform").serialize(),
beforeSend:function()
{
$("#loading").show();
},
complete:function()
{
$("#loading").hide();
},
success: function (resp)
{
if(resp.status == 0)
{
$('#message').css('color','red');
$('#message').html(resp.error).show(400);
}
if(resp.status == 1)
{
$('#message').css('color','green');
$('#message').html(resp.msg).show(400);
}
if(typeof(resp.error) != 'undefined')
{
if(resp.error != '')
{
alert(resp.error);
}else
{
alert(resp.msg);
}
}
},
/*error: function (resp, status, e)
{
alert('ajax error :: '+e);
} */
}
);
try like this
$data = $this->upload->data(); //remove comment
/*echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $data['file_name']; // add this line
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
for error try like this
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
exit;
}
I'm getting some problems trying to set order number if sequence of checkbox checked with javascript:
<?php
for ($x=0; $x<count($UnidadesServicio); $x++){
$idunidadserv = $UnidadesServicio[$x]['idunidadserv'];
$unidadserv = utf8_encode($UnidadesServicio[$x]['lugarunidad']);
$desunidad = utf8_encode($UnidadesServicio[$x]['desunidad']);
?>
<tr>
<td width="10%"><input type="checkbox" id="cbx_<?php echo $idunidadserv;?>" name="chk_unidadserv" value="<?php echo $idunidadserv;?>" onClick="AgregarUnidadServ()" /></td>
<td width="56%" height="28"> <?php echo $unidadserv;?> </td>
<td width="13%"> </td>
<td width="21%" align="center"> <input name="txt_orden_<?php echo $x;?>" type="text" id="txt_orden_<?php echo $idunidadserv;?>" value="" size="2" maxlength="1" class="txtorden" /> </td>
</tr>
<?php
}
?>
My JavaScript function:
<script>
function AgregarUnidadServ(){
var group = document.getElementsByName('chk_unidadserv');
var i;
for (i=0; i<group.length; i++){
if (group[i].checked == true){
var id = parseFloat(i+1);
$("#txt_orden_"+id).val(i);
}
}
}
</script>
What i need to to do:
When check any checkbox, set in input text the sequence number (1, 2, 3, etc.)
That code, display like this:
Greetings.
$("#txt_orden_"+id).val(id);
And sequence will start from 1.
Line: 670 which is startdate.value = hiddenstart.value;
But I am getting an uncaught TypeError:
Cannot read property 'value' of null in the javascript console.
Problem is that this only happens in Chrome and no other browser.
Could someone take a look and let me know if there is anything I can change to get this sort out.
<script language="Javascript">
function calcEndDate(cal) {
var startdate = document.getElementById("<?php echo columnnames($value); ?>_0");
var hiddenstart = document.getElementById("hiddenstart");
startdate.value = hiddenstart.value;
var date = cal.date;
var time = date.getTime();
var hiddenend = document.getElementById("hiddenend");
var date2 = new Date(time);
hiddenend.value = date2.print("%d-%b-%Y 23:59");
var enddate = document.getElementById("<?php echo columnnames($value); ?>_1");
enddate.value = hiddenend.value;
return true;
}
function calcUpdateEndDate() {
var enddate = document.getElementById("<?php echo columnnames($value); ?>_1");
var hiddenend = document.getElementById("hiddenend");
enddate.value = hiddenend.value;
}
</script>
<table cellpadding="0" cellspacing="3" border="0">
<tr>
<td><input type="text" class="standardfield_date_srch" name="<?php echo columnnames($value); ?>_0" value="<?php echo $dateoutput0 ?>"></td>
<td><img src="/images/icons/calendar.png" id="<?php echo columnnames($value); ?>0" style="cursor: pointer;" title="Date selector"></td>
<td><input type="hidden" class="standardfield_date_srch" name="hiddenstart" value=" <?php echo date("d-M-Y",time()) ?> 00:00">
<script language="javascript">Calendar.setup({ inputField:"hiddenstart",button:"<?php echo columnnames($value); ?>0",align:"Ll00", ifFormat:"%d-%b-%Y %H:%M", showsTime: true, onUpdate : calcEndDate});</script>
</td>
</tr>
<tr>
<td><input type="text" class="standardfield_date_srch" name="<?php echo columnnames($value); ?>_1" value="<?php echo $dateoutput1 ?>"></td>
<td><img src="/images/icons/calendar.png" id="<?php echo columnnames($value); ?>1" style="cursor: pointer;" title="Date selector" >
<td><input readonly type="hidden" class="standardfield_date_srch" name="hiddenend">
<script language="javascript">Calendar.setup({ inputField:"hiddenend",button:"<?php echo columnnames($value); ?>1",align:"Ll00", ifFormat:"%d-%b-%Y %H:%M",showsTime:true, onUpdate : calcUpdateEndDate});</script>
</td>
</tr>
</table>
Give me some hint or direct me where i wrong.
You're trying to access the hidden fields by id, but as there is no id set hiddenstart and hiddenend are null.
<input type="hidden" class="standardfield_date_srch" name="hiddenstart" id="hiddenstart" value="<?php echo date("d-M-Y",time()) ?> 00:00" />
<input type="hidden" class="standardfield_date_srch" name="hiddenend" id="hiddenend" />