I have a piece of JavaScript code that keeps throwing an 'Is Undefined' error.
< script language = "javascript"
type = "text/javascript" >
// fuction added for click on submit - dp0jmr 05/23/2018
function checkScheduleAndAmount() {
var ppAmt = (double)
<%=p.getPaymentPlanAmt()%>;
var totalamt = (double) document.getElementById("sum").innerText;
if (ppAmt != totalamt) {
alert("The Payment Plan Schedule does not add up to the total Payment Plan Amount - this Payment Plan cannot be submitted." +
" Please correct the Amounts entered and submit the Payment Plan Schedule before leaving this page." +
"\n\nIf the Date Range you have entered does not allow you to enter the Plan you desire, please End this Payment Plan " +
"and begin a new one." +
"\n\nIf you know the installment amount you wish to use, you can enter an installment amount at the start of a new " +
"Payment Plan, and the application will calculate the final payoff date for you. ");
return false;
} else {
return true;
}
}
<
/script>
I've eliminated as many possible culprits as I could:
I've tried every combination of script definitions - there is some JQuery in addition to this JavaScript, but it was running fine alongside it until recently.
I tried putting it inside the page element with no effect.
I don't see any obvious syntax errors - all the variables being used here are defined.
The function call is on an html:button tag, at the very bottom of the div.
<html:submit property="submitValue" value="<%=PaymentPlanDetailsForm.SUBMIT%>" styleClass="button" disabled="<%=isActive %>" onclick="return checkScheduleAndAmount()" onkeypress="return false"/>
This started to occur recently after refining my JQuery function, but both functions seemed to be working fine during testing, and even seemed to work without issue together for awhile - and unfortunately, I cannot revert my changes now because I made the mistake of closing the IDE. :(
Am I missing something obvious in the syntax for this? Or is there another reason my page isn't recognizing my javascript function?
This JavaScript code:
var totalamt = (double) document.getElementById("sum").innerText;
...is invalid JavaScript code, and so the parsing fails, and the function isn't created.
JavaScript is not C# or Java or (insert language here). It doesn't have casting. Just remove the (double) part. If you want to convert that string to a number, use a unary +, the Number function, parseInt, or parseFloat.
For instance, if you want to convert all of the text to a number, and treat a blank as an invalid input, then:
var str = document.getElementById("sum").innerText;
var totalamt = str ? +str : NaN;
if (isNaN(totalamt)) {
// ...it wasn't a valid number
}
As I mentioned, you could also use parseInt or parseFloat, but beware that they accept numbers with trailing non-numeric characters (parseFloat("123.4abc") is 123.4, for instance).
Related
this is my second post today as the original wasn’t clear and I was urged to repost because despite getting some good answers they did not fit the requirements of the code. I have been challenged to write a program in JavaScript that allows the user to perform several tasks, one of which is to ask the user for a number and calculate the factorial of that number and then display it in the format listed in the requirements. As I do not know much about Java script I used already asked questions and managed to get the calculation to work but could not figure out how to get the required output whilst still meeting the requirements.
Requirements:
• Can only use the provided variables Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation). This is a limitation set by the challenge and not me
• Cannot use fancy libraries
• Need to use a loop solution for the output. The answers on the other post required introducing new variables, perhaps it is my lack of understanding but perhaps the poorly written pseudo code I have obtained since the last post may help.
• Be output in the format: (it is an alert so that part of the program is fine)
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Poorly written pseudo code:
Code:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions, including my first post which this one now succeeds as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but do not know where to begin implementing that and I'm only allowed to use that solution.
Again, I would like to apologise for my first post, the given answers would work great if not for the incredibly ridiculous restrictions set by the challenge provider, who is also responsible for giving me rubbish pseudo code, which isn't what I'm going for but I am using to consider the loop.
I appreciate the time it takes to read this amd provide solutions so I will go back and try and mark all working answers in the last post for any normal problems people might search for answers for.
This is a bit of a dirty hack but it should satisfy the condition that no other variables than number, count, and factorial are used.
let number = 5;
let factorial = 120;
// ^ Do your own calculation for this
alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)
So what is going on here?
We use an interpolated template string to produce the desired output, expressions inside ${these things} are evaluated as strings. And what is the mess we put in there?
Array.from(Array(number + 1).keys())
The expression above creates the array [0,1,2,3,4,5].
.slice(1) gives us [1,2,3,4,5]
.reverse() gives us [5,4,3,2,1]
join("*") gives us "5*4*3*2*1"
Which when all put together gives us The factorial of 5 is 5*4*3*2*1=120
And voila! The output is printed in the desired format without introducing any new variables.
Edit: Oh and you do not need to use an interpolated string for this. You may as well concatenate regular strings together as you have done in your question. e.g.
"The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial
System.FormatException: Input string was not in a correct format.
it is because the input expected should be numbers only but my input must be in the format of 555-555-5555 that is a requirement. here is my js to do so:
$(window).load(function () {
$("#phoneNumber").inputmask("***-***-****");
});
And here is my C# to render the value in this format (555)555-5555, the issue happens here
public static string phoneFormat(string phone)
{
//string[] splitNr = phone.Split('-');
// return ("(" + splitNr[0] + ")" + splitNr[1] + "-" + splitNr[2]);
string[] number = phone.Split();
return string.Format("{0:(###) ### - ####}",ulong.Parse(phone));//ERROR
}
if i use the commented out part it works but i want to use the parse way. How do i remove the "-" in C# after user input it in the UI and then display the number in this format (555)555-5555.
Thank you
It is easier to handle it as a string instead of trying to parse and then format it as number:
return Regex.Replace(phone, #"(\d{3})-(\d{3})-(\d{4})", "($1) $2 - $3")
For fun we can do this:
return string.Format("{0:(###) ### - ####}",ulong.Parse(phone.Replace("-", "")));
But what I'd really do is remove the input mask. Yes, use html/javascript to help the user put in good data, but do so in a way that's much more permissive. If I put in 5551234567, 555.123.4567, (555)123-4567, or even much worse, you should be able to handle any of those.
Input masks are usually bad UI/UX.
On the C# end, I'd really separate this into two parts: normalization, where I clean up potentially messy input for storage and validation, and formatting, where I take the normalized data and format it for display. The reason for two steps is because it's often much more efficient in terms of storage and indexing to store a basic (unformatted) value. Even better, sometimes users want to see the same data represented in different ways. Now it's easy for me to have different format options for the same value. Some people will also include validation as it's own phase, but I like to do this as part of normalizing the data.
Thus, for a really basic phone number, I'd handle the code like this:
public static string NormalizePhone(string phone)
{
// **We should give the user the benefit of the doubt.**
// I don't care what crazy format they used, if there are 10 digits, we can handle it.
//remove anything not a digit
var digits = Regex.Replace(phone, #"[^\d]", "");
//ensure exactly 10 characters remain
if (digits.Length != 10) throw new InvalidArgumentException($"{phone} is not a valid phone number in this system.");
return digits;
}
// Phone argument should be pre-normalized,
// because we want to be able to use this method with strings retrieved
// from storage without having to re-normalize them every time.
// Remember, you'll show a repeat value more often than you receive new values.
public static string FormatPhone(string phone)
{
//Even better if you have an Assert() here that can show phone is always pre-normalized in testing, but works to a no-op in production.
return Regex.Replace(phone, #"(\d{3})(\d{3})(\d{4})", "($1) $2 - $3");
}
Now your existing code can call them together:
try
{
FormatPhone(NormalizePhone(phone));
}
catch(InvalidArgumentException ex)
{
// This won't happen often.
// The html/js layer should stop it in most cases,
// such that we meet the rule of reserving exception handling for actual exceptional events.
// But you'll still want to add a meaningful handler here.
}
But really, I would call NormalizePhone() by itself, to have that raw value ready to save to the user's record, and then FormatPhone() afterwards, to show the user on the screen.
Finally, this is a simplistic port. Real phone number validation can be quite complicated. The link is pretty much the standard work in the area, and it's a whopping 12Mb of raw code.
The scenario is...
A visitor comes to my landing page and completed the form, which included a telephone number.
Using Zapier I then pass that form data to ActiveCampaign.com using a "ZAP".
However as ActiveCampaign is in USA, they require the phone number formatting to international standard, instead of local UK.
Most numbers in UK are 07788990022
But it needs to be presented as +447788990022
So I need to use this built in function of Zapier listed below
https://zapier.com/help/code/
And need some Javascript code writing that will check the number
Is it valid UK mobile number? I.e. 11 digits
Remove all spaces, and trim
If 2nd character is a 7 then replace 1st character (which should be a 0) with +44
I really dont have any idea how to do this! I was hoping for a built in function on Zapier, but apparently not. Any ideas would be awesome!!!
David here, from the Zapier Platform team.
This seems like a pretty straightforward js question! This will be pretty "dumb" validation, but will work assuming the input is correct.
You'll have a code (javascript) step and set the input to be phone: input from step 1. Your code will look like this:
var ph = inputData.phone.replace(/\s+/g, '') // remove all whitespace from string
if (ph.length !== 11) {
// invalid phone number. do nothing?
return []
}
if (ph[1] === '7') {
ph = '+44' + ph.substr(1)
}
return {formattedNumber: ph}
I am trying to create a simple online calculator that can run basic calculations in JavaScript.
I have managed to create the interface so that numbers and operators and stored in a form field.
What I would like to be able to do is pass the values within the form field to a function that will calculate the total of the form field.
The form field could contain anything from a simple "10 + 10" to more complex equations using brackets. The operators in use are +, -, *, and /.
Is it possible to pass the form field's text (a string) to a JavaScript function that can recognize the operators and the perform the function of the operation on the values?
A possible value in the text field would be:
120/4+130/5
The function should then return 56 as the answer. I have done this in JavaScript when I know the values like this:
function WorkThisOut(a,b,c,d) {
var total = a/b+c/d;
alert (total);
}
WorkThisOut(120,4,130,5);
What I would like to be able to do is pass the full value "120/4+130/5" to the function and it be able to extract the numbers and operators to create the total.
Does anyone have any ideas on how this could be done or if it is even possible? this may get more complex where I may need to pass values in parentheses "(120/4)+(130/5)"
I may get blasted for this. But, here it goes anyway.
There are three solutions I can think of for this:
Implement your own parser, lexer and parse out the code.
That's not super easy, but it may be a great learning experience.
Run an eval under a subdomain meant only for that, so that scripts can't maliciously access your site
Sanitize the input to contain only 12345678790+-/*().
eval(input.replace(/[^0-9\(\)\+\-\*\/\.]/g, ""));
Please blast away with tricks to get around this solution
You can use the expression parser included with the math.js library:
http://mathjs.org
Example usage:
math.eval('1.2 / (2.3 + 0.7)'); // 0.4
math.eval('5.08 cm in inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
It is pretty hard to do much damage with eval if you don't allow identifiers.
function reval(string){
var answer='';
if(/^[\d()\/*.+-]+$/.test(str)){
try{
answer= eval(str);
}
catch(er){
answer= er.name+', '+er.message;
}
}
return answer;
}
what about eval?
consider calc as the id of textfield. then
$('#calc').change(function(e){
alert(eval($(this).val()));
})
but remember to validate input before processing.
This is a pretty old topic, but for the new visitors who have similar problem: the string-math package calculates the [String] equations like in the sample above 120/4+130/5. It also recognizes parentheses.
I need to compare a float value entered in a web form against a range. The problem is that the client computers may have various locale settings, meaning that user may use either "." or "," to separate the integer part from decimal one.
Is there a simple way to do it? As it is for an intranet and that they are only allowed to use IE, a VBScript is fine, even if I would prefer to use JavaScript.
EDIT: Let me clarify it a bit:
I cannot rely on the system locale, because, for example, a lot of our french customers use a computer with an english locale, even if they still use the comma to fill data in the web forms.
So I need a way to perform a check accross multiple locale "string to double" conversion.
I know that the raise condition is "what about numbers with 3 decimal digits", but in our environment, this kind of answer never happen, and if it happens, it will be threated as an out of range error due to the multiplication by a thousand, so it's not a real issue for us.
In Javascript use parseFloat on the text value to get a number. Similarly in VBScript use CDbl on the text value. Both should conform to the current locale settings enforce for the user.
This code should work:
function toFloat(localFloatStr)
var x = localFloatStr.split(/,|\./),
x2 = x[x.length-1],
x3 = x.join('').replace(new RegExp(x2+'$'),'.'+x2);
return parseFloat(x3);
// x2 is for clarity, could be omitted:
//=>x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1])
}
alert(toFloat('1,223,455.223')); //=> 1223455.223
alert(toFloat('1.223.455,223')); //=> 1223455.223
// your numbers ;~)
alert(toFloat('3.123,56')); //=> 3123.56
alert(toFloat('3,123.56')); //=> 3123.56
What we do is try parsing using the culture of the user and if that doesn't work, parse it using an invariant culture.
I wouldn't know how to do it in javascript or vbscript exactly though.
I used KooiInc's answer but change it a bit, because it didn't reckon with some cases.
function toFloat(strNum) {
var full = strNum.split(/[.,]/);
if (full.length == 1) return parseFloat(strNum);
var back = full[full.length - 1];
var result = full.join('').replace(new RegExp(back + '$'), '.' + back);
return parseFloat(result);
}
Forbid using any thousands separator.
Give the user an example: "Reals should look like this: 3123.56 or 3123,56". Then simply change , to . and parse it.
You can always tell user that he did something wrong with a message like this:
"I don't understand what you mean by "**,**,**".
Please format numbers like "3123.56."