javascript var limit, value not exceeding 127 - javascript

I am facing a strange issue in the below javascript code. From a page, the values which are getting pushed in project_list array are project_id (value range from 1 to 150) and bid_amount (value range from 1 to 2000). Everything works fine apart from one thing, whenever value of project_id (sent from page) is greater than 127, the value getting inserted in code line project_id = project_list[i]; is 127. As I checked, var does not have such a low limit. Also this code line bid_amount = parseFloat($("#bidAmount_"+project_list[i]).val()); works fine, easily taking value greater than 127. Please help, I have not declared shortint anywhere!
function bid_project_tournament(current_round)
{
var i;
var project_list= [];
$('#B2WProjectList :checkbox:checked').each(function(i){
project_list.push($(this).val());
});
$("#bid_project").attr("disabled","disabled");
var project_id;
var bid_amount;
var bid_data="0";
for(i=0;i<project_list.length;i++)
{
project_id = project_list[i];
bid_amount = parseFloat($("#bidAmount_"+project_list[i]).val());
bid_data = bid_data+";"+project_id+","+bid_amount;
}
}

We figured out the reason for this specific problem in the comments (a column with the type TINYINT instead of INT), but I'll leave a more general answer in case people come here with similar problems.
If you find that numbers are being capped at or around some power of two when sent to the server, there's a good chance the problem lies somewhere in your back-end code or database. Here are some things to check:
Have you accidentally set a column in your database to BYTE, TINYINT, SMALLINT or similar instead of INT or larger? Check your column definitions!
Are you passing the value to a variable in your back-end code which has a type like short, word, byte or similar?
If the values are in pre-filled HTML form fields, have you checked if the values in that HTML are correct?
If everything above checks out, fire up your browser's debug tools and watch the network activity panel to confirm if the values are being capped on the client.
There's no (reasonable) limit to the value of a checkbox in HTML, or indeed to any field without any restriction like a max or maxlength attribute. The biggest number you can represent in JavaScript without losing precision is 9,007,199,254,740,992, so if your numbers are being capped or rounded above that value, the problem might be JavaScript.

Related

Why does the divide portion make the outshow as NaN

my code below works to add all the values together and displays the total, when I try an divide the items (/ val.flowers) it outputs NaN.
trimPerFlowerA(){
let lineA = this.model.processed.filter(val => val.originatingLine === 'A');
if(lineA.length > 0)
return lineA.map(val => {
return (val.trimA+val.trimB+val.trimC+val.flowerOilGrade/val.flowers)
}).reduce((a,b) => a+b,0);
return 0;
}
If I were to place a bet, I would say that you have some undefined lurking around.
This problem really depends on your input data and therefore on the contents of this.model.processed.
On a general basis, a number of calculations in JavaScript can result in NaN.
Some typical cases are:
"A"/0
"A"/"B"
0/"A"
0/0
NaN/0
0/NaN
NaN/NaN
undefined/10
1/undefined
However, in your specific case it's also possible that the problem is not in the division but in the sum within the (val.trimA+val.trimB+val.trimC+val.flowerOilGrade/val.flowers) expression.
In particular, you can have NaN also for:
NaN+1/10
undefined+1
And all similar expressions.
I would recommend putting some breakpoints around and verify the individual values. If the amount of entries doesn't lend itself to breakpoints, try and put some console.log on those same values and then check them. This should allow you to pinpoint the specific value (or values) that cause the output to be NaN.
Also, once you found the issue, you will probably want to cover your base by adding unit tests working against both valid and invalid input data.

Local Storage not stored after page refresh

I'm having a really hard time understanding what I did wrong in my code in order to have a value saved in local storage.
I have a pretty big code project so I'll try to summarize what the program is tryin to do overall.
I am pulling news articles from the news API and displaying the articles; each article (depending on the publication it came from) pushes a different numeric value into an array allSource2.
I then take the sum of this array to arrive to a "score" (variable is called sum)
I basically want that score to be locally stored, so that it is available even after a page refresh.
I think something wrong might be happening because of where I put the localStorage function. Currently I put it under the click event that also pushes the numeric value in the array (when you click the article title).
I am super confused at where else it could be, so that it truly updates the sum every time that sum changes.
Also, it does work to store it (I checked localStorage on the console, after a refresh it still works, but after refreshing and then clicking on another article, it resets to whatever the value of this article is)
I didn't put the entire code, as it's insanely long. everything else is working fine, it's just that.
Also, the all of this is contained within one big function
I define let sum =0; at the beginning of the code.
Then, this is the click event.
document.getElementsByClassName('article-rating')[i]
.addEventListener('click', function(event) {
sum = allSource2.reduce((tempSum, val) => tempSum + val);
console.log("article score is now" + " " + sum);
var lastname = localStorage.getItem("overallsum");
localStorage.setItem("overallsum", sum);
});
I also tried to put the var lastname = localStorage.getItem("overallsum"); at the beginning of the code, when the first function but no luck.
Thanks a lot for your help!
and apologies for any formatting issues, I'm super new to this.
Each time you click the event the overallsum is getting set and that is the problem. If the overallsum is a one time store to the local storage then you can check if the value of overallsum is null, and if so store the value for the first time.
Example:
if (localStorage.getItem("overallsum") === null) {
localStorage.setItem("overallsum", sum);
}
Otherwise, if the overallsum is something, then for every individual article you could 2D array and then set the value with the same conditional check.

Correct way to have calculated values in React.js

Setup
So basically I have 3 dimension fields (length, width and height) that are backed by state. I want to keep the state in inches but allow the user to switch the units on the display at will. Currently I'm only supporting inches and feet so I have a "dimension_unit" state that stores the currently displayed units and display_dimensions_multiplier that stores 1.0 for inches and 1.0/12.0 for feet (both are in state). I have everything working exactly as I want except for one thing.
Problem
All values I've tried have worked except when you try to use a decimal. Basically, in the background it's running throw the multiplier to get saved in state on change and then multiplies back in the value for the field which basically erases the trailing "." as you type so say you were trying to type 4.5, what you would actually get in the field as you typed is 45. But if you type 45 and then move the cursor between the 4 and 5 add the . you'll end up with 4.5...
My idea
The way I was thinking about solving it was basically have a state variable for the display_length and then have the regular length state as well then have the display_length stay the same unless they change units and have the length calculated and stored on change and then just persist that... and the same for height and width... but that seems very un-react-ive so what is the react-ive way of doing this? Or is that it?
Happy to post example code if needed, but there is a good bit of code for any component so... yeah... hopefully just the explanation is enough.
Edit1
Basic before fiddle: before
This is my idea I'm curious about: after
The main difference being:
_handleChange: function(ev){
ev.stopPropagation()
ev.preventDefault()
var key = ev.target.name;
var value = ev.target.value;
var indims = this.state.input_dimensions;
indims[key] = value;
this.setState({input_dimensions: indims});
value = (value / this.state.display_dimensions_multiplier);
var dims = this.state.dimensions;
dims[key] = value;
this.setState({dimensions: dims});
},
I think your solution is the right idea. A few similar ideas:
Only update your stored value when the input is committed (for example onBlur instead of onChange). You can apply generic realtime input validation to make sure it's a valid number.
Like you say use a separate "display" state (I would consider this an "input state") and when the component updates with the new stored value, only update the input state if it differs (when converted to the same units). This way you don't need to persist or worry about the "input state" outside the input components.
When the input has focus, don't update the input state when the stored value changes. When the input does not have focus or blurs, update the input state to the stored value.
I don't know that any of these solutions or the one you proposed is more "Reacty" than the others. I think it's really up to you.

Adobe Acrobat - Error Iterating Over All Fields in a PDF with JavaScript

I'm having trouble iterating over all of the fields in my document to remove the tooltip. Here's my code:
var index=0;
while(index<this.numFields)
{
var nom=this.getNthFieldName(index);
var fieldName=this.getField(nom);
fieldName.userName = "";
index=index+1;
}
I'm getting an error saying fieldName is null and my script won't run. I've seen this answer already:
Iterating over all fields in a PDF form with JavaScript
I get the same error with that code too. If I manually assign a field name to fieldName using var fieldName=this.getField("field1");, it works fine.
Does anyone have any idea why this would error on me?
Edit:
I can iterate over the list and output nom to the console so I know it's grabbing the names of the fields properly. It seems to have trouble dropping that name into the this.getField(nom) statement. No idea why...
Why use while… for this?
Doing exactly the same (setting the mousetip text to a blank string) is simpler using
for (var i = 0 ; i < this.numFields ; i++) {
this.getField(this.getNthFieldName(i)).userName = "" ;
}
and that should do it.
However, unless you have a very good reason, setting the userName to the blank string is not recommended; it is needed if your form is used with assistive devices, and it is also the very nearest and simplest help item.
I figured out my issue.
When I created the form, I used the automatic field detection to create my fields for me in order to save time (there are like 250 fields on this form). The reason I needed the script in the first place was to remove the crummy tooltip names that the feature generates.
Apparently, in its infinite wisdom, the field detection feature named a handful of fields with a leading space ( something like " OF INFORMATIONrow1"). Since getNthFieldName(index) returns the fields in alphabetical order, it was returning one of these broken fields and erroring immediately because getField() doesn't like the leading space in the name.
I renamed the handful of fields and the script works like a charm.

Problems with editable-text and beforeUpdate hook (Meteor)

folks. I'm working on my first serious Meteor project, and I'm running into a bit of an issue.
I've got a small page here that contains a table of Categories, and I am using editable-text to allow for edit-in-place functionality for a couple of the fields. Editing seems to work, but to handle some verification, I've written/attached a callback to handle the beforeUpdate callback on the limit field for my document.
The callback seems to be...well...called back, but it's not having the effect on my data that I believe it should have. Basically, if a user types in a value of something like 43, I want this callback to force the value to 43.00 (two decimal places mandatory).
This code segment contains the callback itself:
EditableText.registerCallbacks({
// Callback for editing category limit/budget.
budgetCurrency: function(doc) {
// Variables based on editing.
var oldVal = this.oldValue;
var newVal = this.newValue;
// Verification:
if (isNaN(newVal)) {
// Reject value if not a number, don't make change.
oldVal;
} else {
newVal = Number(newVal);
console.log(newVal.toFixed(2));
return _.extend(doc, {limit: newVal.toFixed(2)});
}
}
});
I'm not sure if I'm doing something wrong or not. The value that is returned via console.log() is just as I would expect it to be, however the same value (in code) is not what ends up being stored in the updated document.
Any assistance would be greatly appreciated. I could just be overlooking something as far as how beforeUpdate works (callback), for all I know.
Documentation for the package in question is located at: https://atmospherejs.com/babrahams/editable-text
What is happening is as expected. Javascript Number cannot be stored directly into mongo. It has to be converted to either an int or a float/double. In your case, it is being converted to an int which does not have decimal points.
Here are your options:
Store the value as a String (and loose the ability to do mongo airthmatic operations such as inc etc.)
Store the value as two separate integers divided between dollar and cents for before and after decimal point.
Use float or double and loose accuracy (only use this if you are storing something approximate as this is not suitable for exact financial values)

Categories

Resources