Obtain and check the value of an input text with javascript - 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.

Related

Chrome/Chromium input number value empty when last char is dot

In Chrome (or other Chromium browser) when I try to get a value of a number input field the value is empty when the last char is a dot (.).
Here is the simplest example I could think of:
<input type="number" oninput="console.log(event.target.value)">
In Chrome when typing for example "123.45" will result in this output:
1
12
123
123.4
123.45
In Firefox I get something more like I would expect:
1
12
123
123
123.4
123.45
Getting valueAsNumber instead of value will result in a NaN if the last char is dot, so no success there either.
Is there a way to get what is is the actual value of the field (or at least the value without the dot) and not something that is already parsed somehow?
UPDATE:
Thanks to #Kaiido I'm a little closer as to why this happens
In my Chrome browser navigator.languages is set to ['en-US', 'en', 'nl'] in Firefox it's set to just ['en-US', 'en']
This explains the difference between the 2 browsers (in my case) and why in Chrome I can use , as well as ..
But I still need a solution for the problem.
The most important thing in my case is that I need a distinction between the field being empty or some other value that somehow can't de parsed to a number. So now the question is more is there a way to get the value of what's actually being types in the field.
Use the 'step' attribute to make it validate and use the locales delimiter.
<input type="number" step="0.01" oninput="console.log(event.target.value)" />
More information:
<input type="number" oninput="console.log('VAL: %s|%s|%s', this.value, this.checkValidity(), this.validationMessage)" step="0.1">
Entering a delimiter not used in the current locale the validity and corresponding message will indicate 'this is not a number', once more digits are entered - up to the limit of precision the step attribute allows - it will parse to valid values again. Your GUI should correspondingly indicate the current validity - if your code requires it to always be usable as a valid number you could save the last value that passed validation, depending on your use case.
Also consider the use of the character "e" which may be cause for a temporary invalid value!

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..

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

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."

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.

JavaScript function to validate an integer value

I'm building a shopping cart and I would like to use a JavaScript function to validate user input when entering the quantity value in the quantity text input. I would like to allow the entering of integer values only (no floats, no other characters).
I know that I can apply this function using onKeyUp event and also I found isNaN() function, but it returns true even for floats (which is not ok).
Can you guys help me out with this one?
Thanks.
You can always check with parseInt:
if (number == parseInt(number))

Categories

Resources