javaScript parseFloat is not working - javascript

parseFloat is not working in our function
There are so many answers abouth this issue but any of them are not satisfying for me.
Please see code:
var kasatoplam = $('.kasatoplam');
function fiyatTopla() {
var eklenen = $('.adisyon .adisyontable .adsiyonTableUrunler').length;
var urunfiyatlari = [];
$('.adisyon .adisyontable .adsiyonTableUrunler').each(function () {
var urunfiyat = $(this).find('.urunFiyati').text()
urunfiyatlari.push(parseFloat(urunfiyat))
});
console.log(urunfiyatlari);
var toplamfiyat = 0;
for(i=0; i<=urunfiyatlari.length; i++){
toplamfiyat += urunfiyatlari[i]<<0;
}
kasatoplam.html(toplamfiyat);
}

`var urunfiyat = $(this).find('.urunFiyati').text()
urunfiyatlari.push(parseFloat(urunfiyat))`
What is the failure mode for parseFloat? Is it throwing an exception or just not yielding the values you expected? It would help to know.
In any case, it seems that the contents of urunfiyat must be the problem. Have you stepped through the code with the debugger and seen what kind of text values you are getting from
` $(this).find('.urunFiyati').text()' ?
Perhaps you are getting nothing undefined or empty string or perhaps the string needs a little processing before it is passed to parseFloat

Related

Heaps permutation algorithm done the opposite way....?

I was trying to use Heaps algorithm the opposite way by fixing elements at the beginning of array instead of last. But Im not able to get the results. Although I understood the theory part of this algorithm, it is confusing when I am trying to implement it. Im mainly confused about the swap statements inside the if condition. (please check comment). It would be helpful if someone can tell what the problem is. Thanks for your time.
function permute(string){
var str = string.split(""), strbrr = [];
function swap(strbrr,index1,index2) {
var temp = strbrr[index1];
strbrr[index1] = strbrr[index2];
strbrr[index2] = temp;
}
function permuteHelper(strarr, curr, end) {
if (curr == end)
console.log(strarr);
else{
var fixed = strarr[curr];
for(i=curr; i<=end; i++) {
permuteHelper(strarr,curr+1,end);
(end+1)%2 ? swap(strarr,end,curr) : swap(strarr,i,end); //This is the most confusing part for me. What is the code here?
}
}
}
permuteHelper(str,0,str.length-1);
}
var string1 = "ABCD";
permute(string1);

Unusal JS code section

So I am a total JS novice, but I had someone write some code to be used within Qualtics survey. That code is now broken and I am trying to fix it up, there is an error with this line:
var timingObj=${e://Field/TimingObj};
I was hoping someone could help explain this line to me so I may be able to fix it up. (I have to full code, but that seemed a bit long to have someone go through.) I understand the first part is setting the variable named timingobj equal to something.
What that is is confusing to me, especially with the "//" which I understand to denote a note and not code. This code had worked in the past but now gives me an error. Any help understanding what I am working with would be amazing.
Thanks!
Update full code as provided to me:
//configurations
var bindInterval=10;
//initiate
var timingObj=${e://Field/TimingObj};
timingObj.version=3;
var startTiming=function(tag){
var currentTimeObj=timingObj[tag];
if (!currentTimeObj) {
currentTimeObj={};
currentTimeObj.startTimes=[];
currentTimeObj.elapseTimes=[];
currentTimeObj.totalElapsed=0;
timingObj[tag]=currentTimeObj;
}
var time=(new Date()).getTime();
currentTimeObj.startTimes.push(time);
currentTimeObj.startTime=time;
timingObj.activateTag=tag;
};
var closePopupCallback=function(){
//stop timing
var time=(new Date()).getTime();
var currentTag = timingObj.activateTag;
var currentTimeObj = timingObj[currentTag];
var elapsed=time - currentTimeObj.startTime;
currentTimeObj.elapseTimes.push(elapsed);
var totalElapsed=currentTimeObj.totalElapsed + elapsed;
currentTimeObj.totalElapsed=totalElapsed;
Qualtrics.SurveyEngine.setEmbeddedData(currentTag+'_Time',totalElapsed);
Qualtrics.SurveyEngine.setEmbeddedData(currentTag+'_Count',currentTimeObj.startTimes.length);
var timingObjSerialized=Object.toJSON(timingObj);
Qualtrics.SurveyEngine.setEmbeddedData('TimingObj',timingObjSerialized);
};
var bindCloseEvent=function() {
//window.document.observe('dom:loaded',func) and document.observe('dom:loaded',func) did not work
var closeButton=$('bottomNavClose');
if (closeButton) {
closeButton.observe('click', closePopupCallback);
} else{
setTimeout(bindCloseEvent,bindInterval);
}
};
// bad smell
var bindLightBoxCloseEvent=function(){
var lightBox=$('lightbox');
if (lightBox) {
lightBox.observe('click', closePopupCallback);
} else{
setTimeout(bindLightBoxCloseEvent,bindInterval);
}
};
bindLightBoxCloseEvent();
bindCloseEvent();
Qualtrics.SurveyEngine.addOnload(function(){
});
This should be an easy fix:
try:
var timingObj = "${e://Field/TimingObj}";
When using Qualtrics piped text in JavaScript, you must enclose the piped text in quotes.
If the piped text is a number that you plan on using and manipulating, as I am assuming, you should use parseInt() to ensure you don't have issues:
var timingObj = parseInt("${e://Field/TimingObj}");
Since the full code makes it clear that the item you are passing in is meant to be an object, I am assuming it is being passed in valid JSON, you should parse it as such:
var timingObj = JSON.parse("${e://Field/TimingObj}");

inovke functions javascript using while

can anyone tell me what is wrong here im just try to invoke this list of functions using array and while if it's possible thanks in advance.
var funciones = ["basicas();", "likeFbk();", "cambiarFondo();"],
i = 0;
while (funciones[i]) {
funciones[i];
i++;
}
jslint show this errors:
91 Expected an assignment or function call and instead saw an expression. funciones[i];
92 Unexpected '++'.
Solved, I use "i += 1;" instead of "i++;" and update the list of functions treated as a string, here is the code:
var funciones = [basicas, likeFbk, cambiarFondo], i = 0;
while (funciones[i]) {
funciones[i]();
i += 1;
}
thank's guys!
try it this way (not sure what you intend to do though, i am guessing you want to iterate unless there is no value at ith index)
var funciones = [basicas, likeFbk, cambiarFondo], i = 0;
while (funciones[i])
{
funciones[i]();
i++;
}
You can't invoke functions like that. The functions array is just a list of strings and not a list of functions. You have two ways of doing this:
Instead of list of strings, use list of functions as below:
var functions = [basicas, likeFbk, cambiarFondo];
while (i in funciones) {
functions[i]();
}
Use eval to evaluate string that contains javascript executable code:
var funciones = ["basicas();", "likeFbk();", "cambiarFondo();"],
i = 0;
while (funciones[i]) {
eval(funciones[i]);
i++;
}
Always go for the first approach, because the second approach is considered as evil.
Or if you prefer
var call = Function.call;
[basicas, likeFbk, cambiarFondo].forEach(call, call);
How this works is left as an exercise.

Cannot read property "0" from undefined. Error Google Apps Script

I´m geting Cannot read property "0" from undefined. Error on line 16. ( while (colunaDias[emptyCell][0] <= dias) )
It should be a very simple function for google SpreadSheets. I can´t see what I´m doing wrong...
The bizarre thing is that if I don´t use the variable "dias" and use a integer instead. The while function works....
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var leadsSheet = ss.getSheetByName("Leads Todas as Categorias, menos outros - Days (5days)");
var targetSheet = ss.getSheetByName("feticaria");
var cellLeads = leadsSheet.getRange(1,1).getValue();
//var cellTarget = targetSheet.getRange(1,1).setValue(valor);
var colunaDias = leadsSheet.getRange('B:B').getValues();
var sourceMedium = leadsSheet.getRange('A:A').getValues();
var emptyCell = 16;
var dias = 1;
while (colunaDias[emptyCell][0] != ""){
while (colunaDias[emptyCell][0] <= dias){
dias++;
emptyCell++;
}
emptyCell++;
}
Logger.log(emptyCell);
}
I think the only thing that could cause that error is if emptyCell is bigger than the colunaDias array, i.e. if your sheet is smaller than 16 rows (if the value you show here is correct).
Add this line right before the first while :
Logger.log('emptyCell = '+emptyCell+' and colunaDias.length = '+colunaDias.length);
I tested a copy of your script and it runs without error except if I define emptyCell > 1000 on a 1000 rows Sheet.
I'm guessing that colunaDias[emptyCell] is undefined. It passes the first while condition, because "undefined" is not equal to "". If colunaDias[emptyCell] is undefined, then either there is something wrong with this line:
var colunaDias = leadsSheet.getRange('B:B').getValues();
or
colunaDias[emptyCell][0]
Where "emptyCell" is 16 is the problem. getValues() returns an object of rectangular grid of values. I would test to see if there is anything in the rectangular grid, by checking [0][0].
Logger.log('is there any data? ' + colunaDias[0][0])
If there is no data, then the something failed on line:
var colunaDias = leadsSheet.getRange('B:B').getValues();
If that line is working, then something higher up is wrong.
You should be checking the return type of getSheetByName for null.
// The code below will log the index of a sheet named "YourSheetName"
var leadsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("YourSheetName");
if (leadsSheet != null) {
Logger.log(leadsSheet.getIndex());
}
I know this post in from a few years ago, but this was the closest to a problem I am having. I just want to post my answer in case someone else ends up here one day.
For some reason the check variable "dias" is being passed as a string.
That's why replacing it with a number allows the script to run.
dias = parseInt(dias); //use this before the variable needs to be read
I cant say why it is passing a string after being ++ but this will fix it

Getting the length of a textbox value or content using JavaScript

This is something that's driving me nuts:
I have this code and it works: I am trying to learn JavaScript before becoming addicted to JQuery. My sample project involves getting the value of the text-box, and validating according to it's length. the name of the form is membership.
Example: This works:
function validateForm()
{
var element = document.membership;
if(element.txtName.value == "")
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
But this doesn't:
function validateForm()
{
var element = document.membership;
var nameLenght = element.txtName.value.lenght;
if(nameLenght < 1)
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
Just an FYI: I am new to JavaScript but very familiar with the syntax. I just want to learn the basics and move up.
I even read some solutions on here but feel I am simply sinking deeper.
Thanks for your help.
May be it is just because of typo in length here:
element.txtName.value.lenght;
must be element.txtName.value.length;.
If you want it to run every time user presses key , then look here: How to check string length with JavaScript
you can use this function as well
var a = txtName.value;
if (a.length < 1) {
alert('your message');
return false;
}

Categories

Resources