Jquery Functions does not work on function parameter - javascript

I have a jquery function which receives a parameter from it callers. Calling split() on the parameter throws error. Here is the function
function formatNairaCurrency(value) {
var formatedWithoutNaira;
var formattedAmount
//check if value is in kobo format
var splittedValue = value.split(".");//Throws error
if (splittedValue.length === 2) {
formatedWithoutNaira = isNaN(splittedValue[0]) ? "" : splittedValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + splittedValue[1];
} else {
formatedWithoutNaira = isNaN(value) ? "" : value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + ".00";
}
return formattedAmount;}
The call var splittedValue = value.split("."); throws the error value.split is not a function
What am I missing?
I am calling this in a .cshtml file. This works in another function even on the same .js file. The difference is that the value was not a parameter but a value from a text box.
Your help is greatly appreciated.

If i understand your intention correctly you are trying to use split for string. Your error could be caused by the fact that value is not string. You need to debug or throw to console 'value'.
Edit: For example if
value is null, or value is undefinded this would most definitely cause your error. Testing for those conditions:
(value === null)
(typeof value === 'undefined')
If your value is number - that would cause error too. You need to cast number to string first. You can do it by
var valueAsString = value.toString();
valueAsString.split('.');

Related

JavaScript: innerHTML outputs undefined, although console.log outputs the right value

I am trying to make a calculator app in JS, and I am struggling with the sine and cosine functions.
The line before
document.getElementByID("screenPar").innerHTML = result;
is
console.log(result);
, and in the console, the correct value shows up, however on the calculator's screen, it says undefined. My function:
function calcSin(){
try{ //Checks for syntax errors
if(calcString[calcString.length-1] == "+" || calcString[calcString.length-1] == "-" || calcString[calcString.length-1] == "*" || calcString[calcString.length-1] == "/"){
throw "Syntax Error"
}
}
catch(err){
document.getElementById("screenPar").innerHTML = err;
return 1;
}
if(calcString[calcString.length-1] == "$"){ //If last character in string is '$', clears screen
clearScreen();
document.getElementById("screenPar").style.color = "black";
}
else{
var evalRes = eval(calcString);
console.log(evalRes + typeof evalRes);
var result = Math.round(Math.sin(evalRes));
console.log(result + typeof result);
clearScreen();
console.log(result);
document.getElementById("screenPar").innerHTML = result;
}
}
calcString is a string of the inputted expression, for instance "3*4*5".
The console outputs the correct value, but innerHTML puts undefined in the paragraph.
I uploaded the code to a free hosting site: brokenCalculator.
What am I missing?
The function you've shown is fine. Something else replaces the screenPar value to undefined.
P.S. Use .textContent instead of .innerHTML unless you desire to add a text as an HTML code.
<button onclick="addToCalcString(calcSin())"...>
Above onclick event you are calling function inside a function. When you click, 1st the calcSin() is getting called and below line is executing fine
document.getElementById("screenPar").innerHTML = result;
But after that the addToCalcString(char) is executing, in which calcString is undefined
document.getElementById("screenPar").innerHTML = calcString;

date.toLocaleDateString is not a function

Have simple function which returns an error:
ERROR: date.toLocaleDateString is not a function
TypeError: date.toLocaleDateString is not a function
at FormatTime (../Src/rootdialog.js:87:58)
Function definition:
function FormatTime(time, prefix = "") {
var date = Date.parse(time);
return ((typeof time != "undefined") ? prefix + date.toLocaleDateString() : "");
}
Function receives Date object as input however even explicit conversion to Date with Date.parse() does not help. Using Node.js 8.x. Any solution?
P.S. Issue was caused by BotBuilder architecture.
Date.parse returns a number. You are looking for new Date. Or, if time already is a Date instance, just use time.toLocaleDateString() (and make sure it really is in every call to the function)!
function formatTime(time, prefix = "") {
return typeof time == "object" ? prefix + time.toLocaleDateString() : "";
}
You can use
new Date(date).toLocaleDateString();
Got this error in a React app, solved it like this:
{ (item.created instanceof Date) ? item.created.toLocaleDateString() : new Date(item.created).toLocaleDateString() }
You're most likely getting NaN as the result of your Date.parse(time) call.
Check the MDN article on Date.parse for the types of input strings it accepts if you think your time argument should be valid.
You may want to modify your return statement so it's checking for failed parses instead of just undefined, e.g.:
function FormatTime(time, prefix = "") {
var date = Date.parse(time); // returns NaN if it can't parse
return Number.isNaN(date) ? "" : prefix + date.toLocaleDateString();
}
function(ng-model_Name,ng-model_Name) {
var fromdate = new Date($scope.ng-model_Name.from.toLocaleDateString());
var todate = new Date($scope.ng-model_Name.to.toLocaleDateString());
return $scope.variable= asign;
}

What does this JavaScript expression in BIRT report mean?

I am working on a BIRT Report and one of the fields contains the following expression:
dataSetRow["user_id"] != dataSetRow["creatorId"] ? dataSetRow["orderCreator"] : ''
What is the logic of this statement?
That statement is the equivalent of the code below, and is called the 'ternary' operator:
var value;
if(dataSetRow["creatorId"]){
value = dataSetRow["orderCreator"];
}
else{
value = '';
}
//To be clear, this isn't assigning to anything - this is the same expression you have in your question.
dataSetRow["user_id"] != value
You could use that expression, which returns a boolean, in an if block, for example:
if(dataSetRow["user_id"] != value){
//Do something
}

"Is not a function" error message at string modification with JavaScript?

I'm trying to modify the value of a string given a condition in a ternary operator statement:
($.trim($("#la").val())) ? a = $("#la").val() : a = 'NaN'
However I'm getting the error message:
"NaN" is not a function
What have I got wrong?
You'd generally do that like this
var a = $.trim($("#la").val()).length ? $("#la").val() : NaN;
or in this case, where an empty string would be falsy, you could do
var a = $('#a').val() || NaN;
The issue with NaN not being a function is probably because you quoted it, so it's a string, but unquoting it wont make it a function, it's still a native property!
var a = ($.trim($('#la').val()).length > 0) ? $('#la').val() : 'NaN';
should give you what you want.
Try this one:
var value = $("#la").val();
var a = ($.trim(value).length>0) ? value : 'NaN';

Type of HTML element returned from document.getElementById String not Number

I am obtaining the value of an HTML element by using document.getElementById.innerHTML, and then passing that value to a function that returns the type of the value. I am then using an if / else if block to print out the type of value to the console. My problem, is that the typeof method always returns a type of string. If I don't use document.getElementById and declare the variable directly, typeof returns the correct type. Thanks for your help!
JS Fiddle here: http://jsfiddle.net/sY7uW/
// get innerhtml of div
var LowTemperature = document.getElementById('LowTemperature').innerHTML;
// check type from function return
if(check_type(LowTemperature) === 'number') {
console.log(LowTemperature + " is a number");
}
else if(check_type(LowTemperature) === 'string') {
console.log(LowTemperature + " is a string");
}
// return var type
function check_type(value) {
return typeof value;
}
innerHTML will only return a string. You will need to parse that to an integer.
How do I convert a string into an integer in JavaScript?
You can try to parse the value as an integer, and then compare this back to the original:
if(parseInt(LowTemperature) == LowTemperature) alert("LowTemperature is an integer");
What's happening here is that you're checking the type of number, which exists in string form. Try this instead:
// return var type
function check_type(value) {
//you could also use parseInt or parseFloat here, but that would return a number for a string like "2014 asdf".
//By multiplying by 1, the value will be changed into a number if it is one
var valueNumber = value*1;
return typeof valueNumber;
}
var LowTemperature = document.getElementById('LowTemperature').value;
or
var LowTemperature = parseInt(document.getElementById('LowTemperature').innerHTML);

Categories

Resources