Form calculations and Javascript PDF Forms - javascript

I have a PDF form that I'm making that adds up 5 fields with javascript.. The script will add all the numbers,but if one field is left blank the total is all screwed up. If I go back and add a zero to the blank field everything works fine. How can I fix this.
this.getField("RUNTOTAL").value = this.getField("RUNRow1").value + this.getField("RUNRow2").value + this.getField("RUNRow3").value + this.getField("RUNRow4").value + this.getField("RUNRow5").value;
OK so I tried this and it doesn't work at all now. Maybe I missed something?
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function getFieldValue(RUNRow1) {
var value = this.getField(RUNRow1).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow2) {
var value = this.getField(RUNRow2).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow3) {
var value = this.getField(RUNRow3).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow4) {
var value = this.getField(RUNRow4).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow5) {
var value = this.getField(RUNRow5).value;
return isNumeric(value) ? value : 0;
]
this.getField("RUNTOTAL").value = getFieldValue("RUNRow1") + getFieldValue("RUNRow2") + getFieldValue("RUNRow3") + getFieldValue("RUNRow4") + getFieldValue("RUNRow5");

This is a consequence of the loose typing of JavaScript. And it hits me every now and then. By default, JavaScript treats the empty string as string, and not as number 0, unless you persuade it to do so.
The simplest way would be multiplying every field value with 1 (which assumes that the fields do contain strings which can be converted to valid numbers).
Therefore, the code would look like this:
this.getField("RUNTOTAL").value = this.getField("RUNRow1").value*1 + this.getField("RUNRow2").value*1 + this.getField("RUNRow3").value*1 + this.getField("RUNRow4").value*1 + this.getField("RUNRow5").value*1;

Related

Advancing numeric string in localstorage

Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.
Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".
function saveTask() {
var task = $("#task").val();
var taskDate = $("#taskDate").val();
if (newUser == null) {
var taskNumber = 0;
localStorage.setItem("taskTracker", "0");
localStorage.setItem("newUser", "no");
}
else {
var taskNumber = localStorage.getItem("taskTracker");
}
var advanceTask = taskNumber + 1;
localStorage.setItem('task' + taskNumber, task);
localStorage.setItem('task' + taskNumber + 'date', taskDate);
localStorage.setItem("taskTracker", advanceTask);
console.log(advanceTask);
displayTasks();
}
If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.
Thoughts? <3
There is a difference between string + number and number + number. Your current solution is like the stringPlusOne function below. You need to convert the string to a number (using parseInt is one way) and then do the math, like the stringPlusOne2 function below
function stringPlusOne(str) {
console.log(str + 1);
}
function stringPlusOne2(str) {
console.log(parseInt(str, 10) + 1);
}
stringPlusOne("2");
stringPlusOne2("2");

how to set single quote in javascript

I want to set javascript variable with single quote. How it is possible. I am passing value to my function as parameter. and I am using this value to retrieve value of checkbox. So my problem is that if I am alerting value then it give me 'user' instead of 'sanjay' Here 'sanjay' is my value which is I am passing to parameter. And this will use to retrieve value of checkbox document.getElementById.
function single(user){
var abc = '\' user \'';
alert(abc);
return false;
var chksingle = document.getElementById(abc).checked;
alert(chksingle);
return false;
if (userlist() === false)
{
return false;
}
else
{
document.tallyexport.method = "post";
document.tallyexport.action = "checksingle.php";
document.tallyexport.submit();
}
}
Use string concatenation. The way you are doing it right now has user as part of the actual string, not using the variable.
var abc = "' " + user + " '"

"Try...Catch" Block not Working with parseInt()

What I'm trying to do:
I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
The above code works just fine, and does exactly what I want it to do for the scope of my program.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
What I'm trying to accomplish with the try...catch block is simply to make sure that
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
are actually numbers.
The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!
Also: I looked at both of these links and was unable to understand my problem.
javascript parseInt return NaN for empty string
http://www.w3schools.com/jsref/jsref_isnan.asp
Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.
You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()
It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And, then there's no reason to use exceptions in your code, so you can just do this:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Also, in your code, some .Value properties look like maybe they should be .value (lowercase).
In your first code block
var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);
You are using Value, which should be value, that's case-sensitive.
By the way, isNaN returns boolean, you don't have to compare with true

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.
Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.
I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.
I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.
Any ideas.
function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";
document.getElementById("qOut").innerHTML=output;
}
function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}
function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
You have a recursive function in your chkScore, but you're not return-ing the results from the "deeper" iterations.
Try this:
function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}
The missing return there, resulted in the function sometimes not returning anything.
The "deeper" iterations will return their value only 1 "level" up, so that "level" will have to pass it through, if you know what I mean.

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources