The user needs to enter the 4 input fields in order to get the result which is expense. The result will be using FV formula thus I searched online and found out the how FV formula can be used in PHP. Now i want to call the function of the FV formula using the jQuery as i want when the user entered all fields the results will auto come out in the id rExpenses but it doesn't work. It displays a blank page when I go the localhost. Can anyone help? Thank you!
Edit: I deleted the php part and change the code to:
<!doctype html>
<html>
<script>
$(document).ready(function() {
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = FV($rate/100,$rage - $age ,0,$rincome,0);
$('#rExpenses').html((rExpenses).toFixed(2));
});
});
</script>
<b>Monthly retirement income (SGD):</b>
<input type="number" id="textfield1" value="<?php echo $_POST['rincome'];?>" name="rincome" min = "0" />
</p>
<p>
<b>Inflation rate (%):
<input type="number" id="textfield2" value="<?php echo $_POST['rate'];?>" name="rate" min = "0" step = "0.1"/>
</p>
<p>
<b>Current age:
<input type="number" id="textfield3" value="<?php echo $_POST['age'];?>" name="age" min = "0" max = "70"/>
</p>
<p>
<b>Retirement age:
<input type="number" id="textfield4" value="<?php echo $_POST['rage'];?>" name="rage" min = "0"/>
</p>
<p>
<b>The monthly expenses when you retire(inflation adjusted):<span id = "rExpenses">$0.00</span>
</p>
<script>
function FV(rate, nper, pmt, pv, type) {
var pow = Math.pow(1 + rate, nper),
fv;
if (rate) {
fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
} else {
fv = -1 * (pv + pmt * nper);
}
return fv.toFixed(2);
}
</script>
</html>
You can't call a PHP function from within JQuery because JQuery is running in the browser, and PHP is running on the server. You could do it as a remote sort of thing using an AJAX call, but that would be silly. Why not just translate the PHP function into Javascript, and have it on the page?
Looking at the page, I can see what you've done, and it looks like you're wanting to have the server do the calculation. If you want to do that, you'll probably have to create a form and post your values to the server, or, as I said above, do something with AJAX.
If it were me, I'd get rid of the PHP stuff, and have something like this instead (and yes, you can use $ signs in variable names in Javascript, but I'd recommend against this if you're going to mix PHP up with it):
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = fv($rate/100,$rage - $age ,0,$rincome);
$('#rExpenses').html((rExpenses).toFixed(2));
});
then change your <?php and ?> tags at the end of the page into <script> and </script> tags. It won't work exactly, but you should be able to debug it easily enough in your browser tools.
I think you are confusing two concepts here. PHP runs on server, which means when you call that php function, the result is a html file without any of the php code. So you cannot directly call php function in jquery, which runs on the generated HTML file.
I think translating the php function to a javscript function, which can be directly called is the best option you have now.
The translated javascript function is as easy as below:
function fv(r,n,p,pv=0)
{
var sum = pv;
for (var i=0;i<n;i++ )
{
sum += sum*r + p;
}
return sum;
}
Then your jquery script block becomes
$(document).ready(function() {
$('input').keyup(function(){
var rExpenses = fv(("#textfield2").val()/100, ("#textfield4").val() - ("#textfield3").val(), 0, ("#textfield1").val());
$('#rExpenses').html((rExpenses).toFixed(2));
});
});
Related
My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})
I am very new to Javascript, only a few weeks, and am stuck on something I assume to be simple. I have searched for hours, but cant find an example to point me in the right direction. Im basically wanting to create a simple "Running Balance" calculator. One textbox has the input (added by using add button) and the other textbox has the output. The output should change depending on what I put into the input textbox and keep adding to the value in the output textbox.
Here is my code in Javascript:
var accountBalance = 0;
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
total = parseInt(inPrice += accountBalance);
document.getElementById("outBalance").value = total;
}
and the HTML:
<form id="form2" name="form2" method="post" action="">
<p>
Enter an amount:
<input type="text" name="inAmt" id="inAmt" />
</p>
<p>
Display Balance::
<input type="text" name="outBalance" id="outBalance" />
</p>
</form>
<p><input type="button" id="addBal" value="Add the amount to the balance" onclick="addBalance()"/></p>
I have a feeling my total variable in my function is what I am screwing up. Thanks in advance for the help!!
This part doesn’t really make sense:
total = parseInt(inPrice += accountBalance);
It takes accountBalance (0), appends it to inPrice (since inPrice is a string), stores the value back in inPrice, parses the result as an integer, and sets total to that integer. What you seem to need is pretty much the reverse, that is:
Parse inPrice so that it’s a number instead of a string
Add it to accountBalance and store the result in accountBalance
Put the new accountBalance in total (or just use accountBalance in the first place)
Or, in JavaScript:
var accountBalance = 0;
function addBalance() {
var inPrice = parseInt(document.getElementById("inAmt").value, 10);
accountBalance += inPrice;
document.getElementById("outBalance").value = accountBalance;
}
You've confused a few variables - the problem was you were never reading the current balance and you were resetting the total variable every time (aside from mixing ints and strings). Here is a version without the total variable:
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
accountBalance += parseInt(inPrice, 10);
document.getElementById("outBalance").value = accountBalance;
}
See it here: http://jsfiddle.net/fdureo1s/
I've been struggling for a while with a problem, which I believe is very simple, yet I'm unable to solve. Can you tell me how to pass data to my function in the current example.
The situation is as follows
I'm generating new form elements with a button. But I would like to add the functionality of counting the word count for the new textareas, currently I'm able to just make it work for the first inputs.
HTML
<textarea class="cTxtW-<?php echo $k;?>" type="text" placeholder="50 word description"></textarea>
<p id="count-<?php echo $k;?>"></p>
<script>
$( ".cTxtW-<?php echo $k;?>" ).keyup(function count('.cTxtW-<?php echo $k;?>', 'count-<?php echo $k;?>'));
</script>
At the top of the page is my javascript
<script type="text/javascript">
function count(txt, cnt){
var txtVal = $(txt).val();
var words = txtVal.trim().replace(/\s+/gi, ' ').split(' ').length;
var chars = txtVal.length;
if(chars===0){words=0;}
$(cnt).html(words+' words');
}
</scirpt>
I'm adding new fields with the following code
var addDivS = $('#addServ');
var k = parseInt($("#lS").attr('rel'))+1;
$('#addNewServ').on('click', function() {
if(k<=5){
var inputsS = '<textarea name="servTxt[]" style="margin:10px 0 0 0;width:560px;height:60px;" class="inpt cTxtW-'+k+'" type="text" placeholder="50 word description"></textarea><p id="count-'+k+'"></p>'
$(inputsS).appendTo(addDivS);
k++;}else alert('Maximum number of contacts reached.')
return false;
});
So my question is - how to show my word count based on the newly generated textarea field?
This should work...
<script>
$( ".cTxtW-<?php echo $k;?>" ).keyup(function () {
count('.cTxtW-<?php echo $k;?>', 'count-<?php echo $k;?>');
});
</script>
You were passing in the result of the count function as an event handler for keyup. By putting it in an anonymous function it will only run it when the even takes place.
This wordpress stuff driving me mad again.
I have an output page which uses a short code to call a function (Stores)... the code of which in part is beneath.
It has a dropdown and a table of data, ..the data being dependant on the selected option of the drop down.
I use javascript to set the hidden input...successfully.
In fact I tried a normal, non hidden input as well...same result,..on server side, with$_POST["txtSelection"] or
$_POST["hdnSelect"]
But when I try get it's value on the php server side code, it is empty,..
How on earth do I retrieve it?
the hidden input is inside the form tag.
<?php
function Stores()
{
global $wpdb;
global $MyPage;
$MyPage = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
?>
<form name="frmSB_stores" method="post" action="<?php echo $MyPage ?>">
<input type="hidden" name="hdnSelect" id="hdnSelect" value="">
<input type="text" name="txtSelection" size="19" id="txtSelection" value="">
<script type="text/javascript">
function SetDDLValueOnChange (objDropDown) {
var objHidden = document.getElementById("hdnSelect");
if ( objDropDown.value.length > '0')
{
objHidden.value = objDropDown.value; //.substr(0,1);
//alert(" hdn = " + objHidden.value);
window.location = '<?=$MyPage;?>' ;
}
}
</script>
the dropdown's markup here,..then
<table width='100%' border='0' cellspacing='5' cellpadding='3'>
<?php
$Area = $_POST['txtSelection']; //or $_POST['hdnSelect']
which has zilch in it , even though it is set successfully by jvascript
Why is this such an issue in WordPress,
How do i overcome it.
It's nuts spending a full day on something which should be so trivial (works fine in a normal php situation, os asp or asp.net,..but not in WP.)!
TIA
N
This doesn't submit the form it just tell the browser to goto that page. Hence your value always empty.
window.location = '<?=$MyPage;?>' ;
Replace that line with this instead.
document.forms["frmSB_stores"].submit();
I'm working on a little parsing thing to color objects.
For an example, you could type red:Hi!: and "Hi!" would be red.
This is my not working code:
<script type="text/javascript">
function post()
{
var preview = document.getElementById("preview");
var submit = document.getElementById("post");
var text = submit.value;
<?php str_replace("red:*:",'<i class="red">*</i>',text); ?>
preview.value = text;
}
</script>
You have at least two massive problems here.
You can't str_replace with wildcards like you are (the asterisks you use are just that - the asterisk character, not a placeholder).
Your idea of the page-rendering process is off - you can't just call some PHP code in JavaScript and have it update the page. Any PHP code will be executed and printed when your page is generated on the server - it can't interact with the page like JavaScript can (JS can because it is executed within the browser, but the browser never actually sees your PHP code as you can check by going to View->Source and seeing what you see). You certainly cannot reference a JavaScript variable from PHP.
Two options.
Option 1 - Proper Server-Side
if you want to colour objects on page load based on post, do something like this:
<?php
# If the value was posted
$raw = isset($_POST['userstring']) ? $_POST['userstring'] : "";
# Split it based on ':'
$parsed = explode(':', $raw);
$colorClass = "";
$text = "";
if (count($parsed) >= 2)
{
$colorClass = $parsed[0];
$text = $parsed[1];
}
?>
<form action="" method="post">
<input type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
<?php if (strlen($text) > 0) { ?>
<i class="<?php echo $colorClass; ?>">
<?php echo $text; ?>
</i>
<?php } ?>
</div>
Option 2 - Proper Client-Side
Include jQuery in your <head> tag to make your life easier. If you really don't want to include jQuery you can still change the jQuery calls to your getElementById etc. (you'll want to replace the html() call with '.innerhtml' I think - just look it up).
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
function post() {
var split = $('#userinput).val().split(separator, limit)
if (split.length >= 2) {
var color = split[0];
var text = split[1];
$('#preview').html('<i class="' + color + '">' + text + '</i>');
}
return false; // Stop form submit
}
</script>
<form action="" method="post" onsubmit="post()">
<input id="userinput" type="text" name="userstring" value=""/>
<input type="submit" value="Submit" />
</form>
<div id="preview">
</div>
</body>
You're mixing server and client side technologies here. The code in the php lock is evaluated once (while still on the server). You're looking for something that will operate entirely on the client side.
This means you need to look into Javascript regular expressions, instead of PHP preg_match type stuff.
http://www.regular-expressions.info/javascriptexample.html
You're looking for this type of thing:
stringObject.replace( regularExpressionVarOrLiteral, replacement );
Josh