How do I get this script to multiply a number that was typed into the input field? - javascript

I'm trying to pull the number that a user types into a text field and multiply that by a number that is already established. (There are other buttons that add +1 or subtract -1 from the total that work just fine. The only problem I'm having is this right here, getting a user's input by them typing in a value to a field and pulling it)
Here's my code:
<!-- HTML Field that I am trying to pull a number out of -->
<input type="text" id="multNumInput">
--
// Creative my variables
var number = 0;
// Creative a variable that is equal to whatever is inputted into the text box
var multNum = $("#multNumInput").val();
// On Button Click, take the number variable and multiply it times whatever the value was inputted in the html
$('#multiply').click(function(){
number = number * multNum;
$('result1').text(number);
console.log(number);
})
Hopefully this is clear enough to understand. As of right now, whenever I click the button, it always changes the number back to 0. That's it. Just 0. No matter what I set the num var to, when clicking the mult button, it always reverts to 0.

You have to convert to number first.
multNum = parseInt(multNum);
number = number * multNum;
//...

First of all, the obvious: Multiplying any number with your number variable which has 0 value will lead to 0 at all times - I suppose you know this but was confused or missed that part, probably by confusing it to initialization of 0 before an addition process. Set it to 1 or another non-negative number and you will probably get better results on the way. :)
In addition, to make it multiply correctly in JS, you have to multiply between two numbers.
Your value is of type String as inserted in your input field.
As already suggested by #Si8, you need to parse it to Number by doing:
multNum = parseInt(multNum);
Also, you seem to be using a text type for your input.
I suggest you set it to a number type, so that you restrict input values:
<input type="number" id="multNumInput">
Check out the Mozilla MDN web docs for more on this.

The answer, as provided by #Robin Zigmond in a comment is this:
"You're failing to convert multNum from a string to a number."

Related

nativeElement.value is NaN if there is a comma

I'm trying to set the number of decimals at 2 in an input. When I type a comma in it, the value becomes NaN so I would like get my number instead of this.
TS
#ViewChild('number') input;
limitNbOfDecimals() {
var regex =
this.form.number.search(/^(\d+(?:[\.\,]\d{0,2})?)$/) == 0
? true
: false;
if (regex == false) {
// Convert the value to a number
var nb: number = +this.input.nativeElement.value;
//set decimals at 2
this.input.nativeElement.value = nb.toFixed(2);
}
}
HTML
<input class="form-control" type="text" [(ngModel)]="form.number"
#number
name="number"
(input)="limitNbOfDecimals()"
/>
EDIT
I manage to add a comma in the number but if I try to add more than 2 decimals after it removes the numbers after the comma like 1,11 -> 1
This isn't a full answer, in the sense of having a total solution, but hopefully helps you get to one (and it's too long for a comment).
The spec at https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number) states:
This specification does not define what user interface user agents
are to use; user agent vendors are encouraged to consider what would
best serve their users' needs. ..... a user agent designed for the
French market might display the value with apostrophes between
thousands and commas before the decimals, and allow the user to enter
a value in that manner, internally converting it to the submission
format described above.
It would seem that the only sure way - if you don't have control over what browsers your users have - of ensuring they can type numbers in the format they are used to in their local setting is to take input as type text and on each keystroke check that they have typed something valid (as you have defined it) and when they submit it convert to a decimal number.
Searching provides code for doing this, depending on exactly what your requirement is for the number formats though you may be better off coding it from scratch.
To add more than 2 decimal values, you need to tell like .toFixed(4) etc..

Integer/decimal user input: how to serialize/store the value

Our stack is currently: React SPA/Apollo/GraphQL/Rails/PostgreSQL.
We have a web form with a number input that maybe (or not) be used to entry decimal values (dynamic/user-created form).
We want the form to be lenient (it has an autosave feature). If user types ,3 or 17,, that is considered a valid number value. But not too lenient, the number should by parseable as a float and be able to display in graphs...
Also, when the user visit the form again, we want to make sure to init the number input with the exact same value he typed initially (I mean, ,3 does not become magically 0,3)
I'd like to know, for our stack, how to serialize (sending as GraphQL payload) and store (in PostgreSQL) and manipulate (in JS/Ruby) such number without loosing the initial user input value.
I'm thinking it would be simpler to send/store a string, as long as it's validated that it can be parsed.
Just wondering if there is a "proper" solution, for example using number libs, custom GraphQL scalar type, decimal SQL type... that seems complicated to me, anyone did something similar before?
Create two fields. One for user input and other with parsed value. I do not think this will be different for any stack.
The challenge is how to show to a user how you understood entered value. This could be solved with a hint with a parsed value under the text field.
you should choose type of the input as "text" instead of number, so you can create a specific format for your input. first, add a property to your state
state={amount:""}
input section for amount in your form should be like this:
<input
type="text"
placeholder="Amount"
value={this.state.amount}
onChange={this.onAmountChange}
/>
onAmountChange = e => {
const amount = e.target.value;
if (!amount || amount.match(/^-?[0-9]\d*(\.\d{0,2})?$/)) {
this.setState(() => ({ amount }));
}
};
regexp in above function means start with any number with optional -, and optionally u can end with 2 decimal number. you can change it for your form.
if you want to add only positive numbers if your form is for price you can use this regexp:
amount.match(/^\d{1,}(\.\d{0,2})?$/)

If statement returning NaN

Am totaling several form fields where users put in hours of the day. However, some users would like to put an "X" if they were not present that day. So I tried several different if statements to try to get the calculation to recognize "X" as a zero when running the calculation but still show an X in the form field. I went as far as creating a hidden form field and default its value to zero and that is the last thing I tried.
Here is my formula (please keep in mind, I will have to use this for each day of the week but I just was playing around with the first one)
var v1 += getField("mon1_str."+row).value;
if(v1 == "X") event.value = "defaultvalue";
else event.value = "";
The first line of script gets my value no problem. Its the second line and third line where i am not having any luck. It should be noted that no errors are coming up in the console window. "defaultvalue" is the name of my hidden form field to grab a value from.
The + tries to convert the string to a number. But 'x' can't be converted to a number, so it results in NaN.
console.log(+'X');
Try saving the plain value, checking if it's 'X', and then converting it to a number later.

AngularJS number input that ignores all keys but numbers

I've been trying to create an input in an AngularJS template and that will only accept whole numbers as input. That is, I don't want it to allow any keys other than 0-9, specifically, I can't stop . from being allowed in the input.
Alexander Puchkov created a directive that achieves this on inputs with type="text" however I want to be able to use type="number" so I can maintain all my other attributes on the field for validation such as min, max, step, etc.
I have an example of this directive not working on a number input here. For example, when type="text" an input of 123. yields a rendering of 123 however when type="number" an input of 123. yeilds 123. since the previous value of 123 is equal when compared numerically.
I'm afraid this simply isn't possible as the following condition is true:
0. == 0
If you perform the following:
setTimeout(() => console.log(element[0].value), 100))
It will always log 0. as 0. This is why ngModelCtrl isnt triggering the parser as no changes are detected.
I would suggest not directly modifying the value of ngModel (as this can also end up leading to users putting in invalid data. ie. pasting 12.00 will resolve to 1200 with your example)
I would add a directive that applies validity depending on if a decimal point is used (technically speaking, typing 0. isn't actually using it. 0.01 is). Set the validity to false if there is a decimal point in the number and display an error message accordingly (via ngMessages). This way the user can correct their own error and can learn from the mistake.

Obtain and check the value of an input text with javascript

I am fairly new with javascript and I need a script to obtain the value of an input text and check that value if it is equal to 0 (zero). If it does then I need an alert message notifying me that the text input is 0. Thanks.
<input id="txtVal" type="text" name="txtVal" value="0" maxlength="10">
The short answer:
if(txVal.value==0) alert('Please enter a number.');
Is not always the best answer:
var v=document.getElementById('txtVal');
v=parseInt(v,10);
if(v<=0) alert('Please enter a positive integer.');
Of course that probably not the best answer either but it does fix a couple of common mistakes.
Although you can refer to an element by using its id as a variable name its not recomended.
The value property of an input (ie txtVal.value) is a string (even if it contains only digits) so if you try to compare it to a number you may get unexpected results. In this case you are comparing it to 0 so problems are less likely but if you ever change your code to compare to another number you will probably run into problems, so its best to make it into an actual number before you do anything with it.
If you want to allow decimals use parseFloat instead.

Categories

Resources