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");
Related
I built an app that I then built with PhoneGap Build.THe purpose is for it to run a code (starts at var Quotes once per day when the app is loaded).
When debugging why it wasn't working I noticed that in console I was getting back my message "Local storage didn't work". This means that my initial localstorage.getItem which is supposed to make sure the local storage can be read is returning null. So my code never gets executed.
What am I doing wrong?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
Initially, there will be no DateOpened item in local storage, so your code will follow the "did not work" branch, because getItem returns null for things that don't exist. That branch never sets anything in DateOpened, so...you'll always follow that branch.
The fix is not to skip over your code setting DateOpened if the device has local storage.
There's also an unrelated problem: Your var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear() does not produce a string, it produces a number formed by adding those values together, since they're all numbers. Your later localeCompare will fail because it's not a string. You also have the fields in the wrong order for a meaningful textual comparison — you need year first, then month, then day.
Here's a minimal fix, see comments:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
I think this is help full for you.
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.
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;
I'm working with the billing part of my system and I put an event in my TextBox using javascript and I have two textboxes. First is the cashonhand and change textboxes. But what I'm wondering is why the comparison between two textboxes is not giving me the right answer. Here is my code:
$(document).ready(function () {
$(document).on('click', '.btn-pay-bill', function () {
var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2);
var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2);
if (cash <= amtdue) {
alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!");
return false;
}
if (cash >= amtdue) {
return true;
}
return false;
});
SO what am I missing here? Here is the output when I compare 100,000 to 78,200.00:
You're comparing alphabetically instead of numerically.
Note that .toFixed() returns a string:
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.
You'll want to do this comparison before you call .toFixed()
var cash = parseFloat(Number($('.cashonhand').val()));
var amtdue = parseFloat(Number($('.amtdue').text()));
if (cash <= amtdue) {
alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!");
return false;
}
You can just call .toFixed() wherever you display the number in the UI, or create a separate string version of the value, such as sCash and sAmtDue or something.
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/ )