I am having a problem with this. My code is working fine but I use it to update then now I have a problem because value is already set.
In this code :
$('#principal').on('input', function() {
calculate();
});
$('#interest').on('input', function() {
calculate();
});
it works when you input a value on a field. But what if I have this code :
<input class="form-control number" name="principal" id="principal" type="text" value="<?php print $fetch['principal']; ?>" required/>
<input class="form-control number" name="interest" id="interest" type="text" value="<?php print $fetch['interest']; ?>" required/>
Value is already set. What code should I use in JQUERY to execute the code without type or editing value from input field.
Sample Output: Edit the value of Principal (What I want is to run compute without clicking or editing something)
$('#principal, #interest').on('input', function() {
calculate();
});
function calculate(){
var principal = $('#principal').val();
principal = principal.replace(/,/g, "");
principal = parseInt(principal);
var interest = $('#interest').val();
interest = interest.replace(/,/g, "");
interest = parseInt(interest);
var total = "";
var total_interest = "";
if(isNaN(interest) || isNaN(principal)){
total_interest = " ";
total = " ";
}
else{
total_interest = (interest / 100) * principal;
total = (interest / 100) * principal + principal;
}
var num = total;
num = addCommas(num);
$('#total').val(num);
var num_interest = total_interest;
num_interest = addCommas(num_interest);
$('#total_interest').val(num_interest);
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
}
$('.number').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Principal:
<input class="form-control number" name="principal" id="principal" type="text" value="9000" required/>
<br><br>
Interest:
<input class="form-control number" name="interest" id="interest" type="text" value="10" required/>
<br><br>
Total Interest:
<input class="form-control number" name="total_interest" id="total_interest" type="text" readonly/>
<br><br>
Total Payment
<input class="form-control number" name="total" id="total" type="text" readonly/>
Simply do this:
calculate();
...in code at the top level of your script. Make sure your script is at the end of body, just before the closing </body> tag.
Example:
function calculate() {
console.log(
"calculating with " +
$("#principal").val() +
" and " +
$("#interest").val()
);
}
$('#principal').on('input', function() {
calculate();
});
$('#interest').on('input', function() {
calculate();
});
calculate();
<input class="form-control number" name="principal" id="principal" type="text" value="42" required/>
<input class="form-control number" name="interest" id="interest" type="text" value="3.7" required/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Side note: You can simplify and consolidate your on calls:
$('#principal, #interest').on('input', calculate);
function calculate() {
console.log(
"calculating with " +
$("#principal").val() +
" and " +
$("#interest").val()
);
}
$('#principal, #interest').on('input', calculate);
calculate();
<input class="form-control number" name="principal" id="principal" type="text" value="42" required/>
<input class="form-control number" name="interest" id="interest" type="text" value="3.7" required/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here's the snippet you added to your answer, with
calculate();
...added to the end:
$('#principal, #interest').on('input', function() {
calculate();
});
function calculate(){
var principal = $('#principal').val();
principal = principal.replace(/,/g, "");
principal = parseInt(principal);
var interest = $('#interest').val();
interest = interest.replace(/,/g, "");
interest = parseInt(interest);
var total = "";
var total_interest = "";
if(isNaN(interest) || isNaN(principal)){
total_interest = " ";
total = " ";
}
else{
total_interest = (interest / 100) * principal;
total = (interest / 100) * principal + principal;
}
var num = total;
num = addCommas(num);
$('#total').val(num);
var num_interest = total_interest;
num_interest = addCommas(num_interest);
$('#total_interest').val(num_interest);
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
}
$('.number').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
calculate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Principal:
<input class="form-control number" name="principal" id="principal" type="text" value="9000" required/>
<br><br>
Interest:
<input class="form-control number" name="interest" id="interest" type="text" value="10" required/>
<br><br>
Total Interest:
<input class="form-control number" name="total_interest" id="total_interest" type="text" readonly/>
<br><br>
Total Payment
<input class="form-control number" name="total" id="total" type="text" readonly/>
You can calculate the result from the server
so from PHP side do the calculate() method and just print it into the result field. as you did with the values, or after your code loaded from js.
or you can use jQuery trigger
$(document).ready(function () {
$('#principal').trigger('input');
$('#interest').trigger('input');
}
Related
I have a table that contains a row with the ability to generate other dynamic rows. The drop-down list works now in every new row that is created. I have the first row. The drop-down list that carries data from the database works well and the data is shown in it well, but when adding a new dynamic row and when Clicking on the drop down list the values written on it all show with the word Undefined all the values of the drop down list written on it show up with the word : Undefined I am really stuck any suggestions would be appreciated and thanks
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
I used an array to print the data in several dynamically generated drop-down lists, but the result is very disappointing and does not bring the expected values from the database in the drop-down lists that I generate when needed, noting that the first drop-down list, which is outside the dynamic generation context, works well and brings the expected data, but the problem is Any new list generated dynamically, the values will only appear with the word "undefined" Any solution will be greatly appreciated...
here problem as GIF amage
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery dynamic genaration code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
1.can someone find why the form doesnt add/submit the values to database ?
i have tried adding values by the form and testing but its not getting in the database
2.and on calculation i get soms values with more than 2 decimals how to fix that because at the script/code i have decimals on 2 maybe someone ?
screenshot of decimals http://prntscr.com/5fbedf
<html>
<head>
</head><body>
<?php require "config.php" ; ?>
<?php require "admin_menu.php" ;?>
<?php
if(isset($_POST['verzenden']))
{
$id = addslashes($_POST['id']);
$flesnummer = addslashes($_POST['flesnummer']);
$begin_gewicht = addslashes($_POST['begin_gewicht']);
$verbruikt = addslashes($_POST['verbruikt']);
$eind_gewicht = addslashes($_POST['eind_gewicht']);
$verschil = addslashes($_POST['verschil']);
$tara_gewicht = addslashes($_POST['tara_gewicht']);
$over = addslashes($_POST['over']);
mysql_query("INSERT INTO Flesnummer (id, flesnummer, begin_gewicht, verbruikt, eind_gewicht, verschil, tara_gewicht, over) VALUES ('".$id."', '".$flesnummer."', '".$begin_gewicht."', '".$verbruikt."', '".$eind_gewicht."', '".$verschil."', '".$tara_gewicht."', '".$over."')");
echo '<br><br><br>Fles succesvol toegevoegd';
}
else
{
?>
<script>
function totaalIt() {
var x = document.getElementById("begin_gewicht").value;
var y = document.getElementById("tara_gewicht").value;
var z = document.getElementById("verbruikt").value;
var w = document.getElementById("eind_gewicht").value;
if ((isNumeric(x, true)) && (isNumeric(y, true)) && (isNumeric(z, true))&& (isNumeric(w, true))) {
x = parseFloat(x);
y = parseFloat(y);
z = parseFloat(z);
w = parseFloat(w);
var wverschil = x - y - z + y - w
var xyzover = x - y - z
var xyztotaal = x - y - z + y;
document.getElementById("verschil").value = wverschil;
document.getElementById("over").value = xyzover;
document.getElementById("totaal").value = xyztotaal;
if (confirm ("Formule: Begin gewicht - tara gewicht = vulling - verbruikt = vulling over + tara gewicht = totaal - eind gewicht = verschil(verlies) ?")) {
document.getElementById("form1").submit();
}
} else {
alert("Numeric Values must be entered.");
}
}
function isNumeric(sText, decimalAllowed) {
if (sText.length == 0) return false;
var validChars = "";
if (decimalAllowed) {
validChars = "0123456789.";
} else {
validChars = "0123456789";
}
var isNumber = true;
var charA;
var decimalCount = 0;
for (i = 0; i < sText.length && isNumber == true && decimalCount < 2; i++) {
charA = sText.charAt(i);
if (charA == ".") {
decimalCount += 1;
}
if (validChars.indexOf(charA) == -1) {
isNumber = false;
}
}
return isNumber;
}
</script>
<form name="form1" id="form1" action=" <?=$_SERVER['PHP_SELF']?> " method="POST">
<table>
<input type="hidden" name="id" >
<tr><td>Flesnummer:</td><td><input name="flesnummer" id="flesnummer" type="text" size"4">
<tr><td>Begin gewicht:</td><td><input name="begin_gewicht" type="text" id="begin_gewicht" size="4" />
Kg</td></tr>
<tr><td>Tara gewicht:</td><td><input name="tara_gewicht" type="text" id="tara_gewicht" size="4" />
Kg</td></tr>
<tr><td>Verbruik:</td><td><input name="verbruikt" type="text" id="verbruikt" size="4" />
Kg</td></tr>
<tr><td>Vulling over:</td><td><input name="over" type="text" id="over" size="4" readonly="true" />
Kg (automatisch berekend)</td></tr>
<tr><td>Eind gewicht:</td><td><input name="eind_gewicht" type="text" id="eind_gewicht" size="4" />
Kg</td></tr>
<tr><td>Eind gewicht: <img title="Eindgewicht volgens berekening" src="img/question.gif" width="15" height="15" onMouseDown="Eindgewicht volgens berekening" alt="Eindgewicht volgens berekening." /></td><td><input name="totaal" type="text" id="totaal" size="4" readonly="true" />
Kg (automatisch berekend)</td></tr>
<tr><td>Verschil(verlies):</td><td><input name="verschil" type="text" id="verschil" size="4" readonly="true" />
Kg (automatisch berekend)</td></tr>
<tr><td><input type="button" name="verzenden" id="verzenden" value="Verzenden" onClick="totaalIt()" /></td></tr>
</table></form>
<?
}
?>
On your form, try turning your button input to submit:
<input type="button" name="verzenden" id="verzenden" value="Verzenden" onClick="totaalIt()" />
TO:
<input type="submit" name="verzenden" id="verzenden" value="Verzenden" onClick="totaalIt()" />
Your button is not registering the name so it's not getting to the $_POST['verzenden'] in your check:
// There is no $_POST['verzenden'] with the button.
if(isset($_POST['verzenden'])) {
I have a function static who can calculate all my static input:
$('document').ready(function() {
$('#input5,#tempsam ').each(function () {
$(this).on('change',recalculate);
});
});
function recalculate () {
if(isNaN(this.value))
alert("Please enter a number");
else {
var b = 0;
if (($('#input5').val() !== b) && ($('#input2').val() !== b) && ($('#tempsam').val() !== b )) {
var a = 40;
var value1 = $('#input1').val() == "" ? 0 : parseFloat($('#input1').val());
var value7 = $('#tempsam').val() == "" ? 0 : parseFloat($('#tempsam').val());
var total = value5 + value2 + value7
$('#result').val(total);
}
}
}
How I calculate my dynamic input and my static one?
Here is how I calculate my static one each day:
//jeudi calcul
function checkfieldjeudi()
{
var dynamicjeudi = document.getElementsByClassName("dynamicjeudi");
var itemCount5 = dynamicjeudi.length;
var total = 0;
for(var i = 0; i < itemCount5; i++) {
total = total + parseFloat(dynamicjeudi[i].value);
total = total + parseFloat(document.getElementById('input5').value);
}
document.getElementById('totaljeudi').value = total;
}
checkfieldjeudi();
How I make dynamic jeudi
$('#calculTempsdivjeu').append(
( '<input id="calculTempsdivjeu' + counterjeudi + '" name="calculTempsdivjeu[]' + '" type="number" onchange="checkfieldjeudi();" size="10" min="0" max="24" value="0" class="dynamicjeudi" onblur="autre();" onfocus="enter();"/>')
) //désactive champs précédent.
Here my static jeudi
<div id="calculTempsdivjeu">
<input step="any" type="number" id="totaljeudi" class="totaljeudi" onchange="checkfieldjeudi();" name="totaljeudi" size="10" min="0" max="24" value="0" onblur="autre();" onfocus="enter();"/>
<input step="any" type="number" onblur="autre();" onfocus="enter();" onchange="checkfieldjeudi();" id="input5" class="temps" name="tempsje" max="24" min="0" value="0" />
</div>
In form, I will be adding product info in. looping name eg. pname1, pname2 when add.
I realise now that when i wanna send to email we need the 'name'. what code should i put on php file to loop the pname?
noted: my form and php code is not in the same file.
or i should put them together and click to loop?
Php file put this?
<?php
$x=1;
while($x<=10)
{
echo "The number is: $x <br>";
echo ;
$x++;
}
?>
form in html
<div class="" id="" name="productlist"> <!-- Add Product Here -->
<ol><input class="fpname" type="text" id="addpname"placeholder="Product Name"/><input class="fpqty" type="number" id="addpqty" placeholder="Quantity"/><input class="fpprice" type="text" id="addpprice" placeholder="Price per Item"/><input type="button" id="padd" value="add"/>
</br><font color="red" size="1.5"><i>*Becareful when adding the Product, once added you are unable to edit the information except changing the quantity.</i></font>
</ol>
<ol id="addhereform"><input type="text" class="fpname" value="Product Name" readonly/><input class="fpqty" type="text" id="pqty" value="Quantity" readonly/><input type="text" class="fpprice" value="Total Price" readonly/>
</ol>
<ol><input class="fpname" id="fpships" type="text" Value="" readonly/><input class="fpqty" id="overallqty" type="text" value="" readonly/><input class="fpprice" type="text" id="overallprice" value="" readonly/>
</ol> <!-- Result -->
</div> <!-- Add Product End Here -->
jquery add button
var count = 1;
$('#padd').click(function(){
var pname = $('#addpname').val();
var pqty = $('#addpqty').val();
var pprice = $('#addpprice').val();
var totalpprice = (pqty * pprice).toFixed(2);
$('#addhereform').append('<li><input class="fpname" type="text" id="pname" name="pname' + count + '" value="' + pname + '" readonly/><input class="fpqty" type="number" id="pqty" name="pqty' + count + '" value="' + pqty + '"/><input type="text" id="pprice" name="pprice' + count + '" value="' + pprice + '" readonly hidden/><input class="fpprice" type="text" id="totalpprice" name="totalpprice' + count + '" value="' + totalpprice + '" readonly/><input type="button" id="premove" value="X"/></li>').before('</li>');
count++;
});
Ans:
$name1 = $_POST["name1"];
$name2 = $_POST["name2"];
$name3 = $_POST["name3"];
# and so on...
for($i = 1; $i <=5; $i++){
$productlist = ${'name' . $i};
echo $productlist;}
Thanks for everyones help,
Here's another method(better) I just found. no need to type all the super long loop way.
Stristr is find name keyword.
if($_POST){
foreach($_POST as $key => $value){
if(stristr($k, 'pname')){
echo "$v";
}
if(stristr($k, 'pqty')){
echo "$v";
}
if(stristr($k, 'pprice')){
echo "$v";
}
if(stristr($k, 'ptotalprice')){
echo "$v</br>";
}
}
}