Number pipe gives string value instead of number - javascript

I have the following lines of code. It's basically an input field in my html. I am adding a number pipe to it since it's a currency field. By default it's empty, when the user adds value to it, it should autoformat it as currency. But am getting a rare issue here.
vendor.dll.js:55094 EXCEPTION: Invalid argument '8,888.038' for pipe 'DecimalPipe'
HTML:
<div class="form-input">
<cust-input
[ngModel]="Amnt | number:'.2-2'"
(ngModelChange)="Amnt=$event"
type="tel"
(keyup)="getAmount(RqstdAmnt)"
[ngClass]="{'inValid-requested-amount-class': AmountValid===false}"
placeholder="{{'amount_placeHolder' | translate}}">
</cust-input>
</div>
TS:
RqstdAmnt:number;
getRequestedAmount(amount:number) {
if (amount > somevalue) {
console.log('value higher');
} else {
console.log('value lower');
}
}
May I know what's the right way to do it? We can have another way, when user clicks on the input field no pipe, when the mouseout add the currency pipe. I am not sure how to do that. Can you guys guide me how can I do that? Thanks in advance.

Using a pipe with ngModel is not the best idea, as when user is typing the pipe will run at every keystroke. I have implemented similar scenario using blur and focus. .00 gets added and removed depending on user input and doesn't interfere with the interaction.
Here's the code if you want to use it in yours:
html:
<md-input-container class="example-full-width">
<input mdInput placeholder="Amount"
type="number"
[(ngModel)]="amount"
formControlName="amount"
(blur)="format(amount)"
(focus)="remove(amount)">
</md-input-container>
ts:
format(amt){
// console.log(amt % 1 == 0);
if(amt % 1 == 0){
amt = amt + '.00';
this.amount = amt;
}
}
remove(amt){
// console.log(amt % 1 == 0);
if(amt % 1 == 0){
this.amount = amt * 1;;
}
}
submit(form){
alert(JSON.stringify(form));
}
Plunker demo

Related

Format Input Type Text without changing the Value

Is it possible to format the text value of an Input element without actually changing the value itself. For example, if I am entering an id number of the following format:
19801010-1234
I wish the value to be 198010101234 but when more than 8 characters are entered, the hyphen should be displayed. I'm using javascript and nodejs.
This is what I currently have:
HTML
<input id="ssn"
className= {styles.input}
type="input"
value= {this.format(personalNumber)}
placeholder={translations.personalNumber}
onChange={this.onChange} />
JS
format(value){
if(value && value.length>8)
return value.slice(0, 8) + " - " + value.slice(8);
return value;
}
I'm using react and the above will of course change the value itself to include a hyphen which I'm hoping I can avoid.
Try this:
<input type="text" id="num"> <span></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function formatVal(num) {
num.length == 8 ? $('#num').val(num+'-') : '';
};
function origVal(num) {
$('span').html(num.replace('-', ''));
}
$('#num').keypress(function() {
formatVal($(this).val());
origVal($('#num').val());
});
</script>
Might not be the best solution. But it works
jsfiddle demo

Limit the user's input in an input number to 4 digits

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.
Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number
Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"
Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />
You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

Angular JS - Using ng-show to show something based on complex requirements

I just started learning Angular JS, and I need a way to use ng-show to show a line of text by considering the following:
1.) If both number fields have been filled in, display the line of text.
2.) If both number fields have been filled in but both are 0, display the line of text.
3.) If both number fields have been filled in and one is 0 but the other is a different number, display the text.
This is my code so far:
<p ng-show="(firstNumber && secondNumber) || (firstNumber == 0 && secondNumber == 0)">
The product is {{firstNumber * secondNumber}}
</p>
Right now, this line of code fulfills requirements 1 and 2, but when 0 is entered and another number is entered which is not zero, the line of text doesn't show.
Any ideas on how to get this done? I feel like the conditional operation statement will be pretty complex.
I think I should include more of my code since many seem to assume that I have "text" as the input type when I have "number". This is probably why Charlie's solution isn't working:
<p>Enter first number: <input type="number" ng-model="firstNumber"></p>
<p>Enter second number: <input type="number" ng-model="secondNumber" /></p>
The collective logic of all your requirements is to see if both fields are numbers.
<p ng-show="isNumber(firstNumber) && isNumber(secondNumber))">
The product is {{firstNumber * secondNumber}}
</p>
In your controller
$scope.isNumber = function(value) {
return !isNaN(value)
}
It's a good idea to encapsulate every piece of complex logic into a function method of your controller or better yet a model i.e.:
.controller('MyCtrl', function($scope){
$scope.isResultVisible = function(){
return $scope.firstNumber >= 0 && $scope.secondNumber >= 0;
};
$scope.result = function(){
return $scope.firstNumber * $scope.secondNumber;
};
});
And then use it inside of markup:
<p ng-show="isResultVisible()">
The product is {{result()}}
</p>

Change the color of an html 5 output object based on value

I want to change the color of the result of a calculation to red if it is negative. I tried a style sheet, and putting the output into a javascript call, but it did not seem to work. Is there a way to change the color of an html 5 output "o" in the example code below to red if it is negative and green if it is positive?
form oninput="o.value = a.valueAsNumber + b.valueAsNumber"
input name="a" id="a" type="number" step="any" +
input name="b" id="b" type="number" step="any" =
output name="o" for="a b">
/form
Not a big fan of just giving answers when users haven't shown what they've tried first but this was actually a bit fun, I've never seen this type of form before.
Like #feeela said, you can use JS to watch for input changes and validate the output field accordingly. I'm using jQuery to do this as such:
$(document).ready(function() {
$('input').change(
function()
{
$('output').removeAttr('class');
var sum = parseInt($('output').first().html());
if (isNaN(sum))
{
$('output').addClass('error');
}
else if (sum < 0)
{
$('output').addClass('negative');
}
else if (sum > 0)
{
$('output').addClass('positive');
}
}
);
});
Then you can use you style sheet to give the output field a colour depending on its class.
​
You can view a demo here: http://jsfiddle.net/S7cVP/

javascript conditional returning unexpected result

I'm doing a simple number comparison on the keyUp event of an input field. For some reason, I'm not getting the expected result, and I can't figure out why. What should happen is that if the user-entered number is larger than that stored in the html attribute, the background should turn red, otherwise it stays white. Simply entering '9' will turn the background red. ??
var admin = $('input[name="diskStorage"]').attr('data-adminstorage'); // 2097152000
$('#new-user input[name="diskStorage"]').keyup(function(){
if(admin < $(this).val())
$(this).css('background','red');
else
$(this).css('background','white');
});
When I debug these values, if(2097152000 < 549) is returning true. Here's the html, in case that makes any difference:
<form action="administrate.php" method="post" id="new-user">
<table><tbody><tr>
...
</tr><tr>
<td>Disk Storage Limit:</td>
<td>
<input type="text" data-adminStorage="2097152000" name="diskStorage" value="" /> megaBytes<br />
<span id="info"></span></td>
...
</tr></tbody></table>
Here it is live: http://jsfiddle.net/JMC_Creative/dqAJj/2/
.attr and .val() return String objects - use the unary + operator to convert it to a numeric value.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage');
admin = +admin;
if(admin < +$(this).val()) {
//...
}
Try adding a /1 after retrieving the admin value, to make it a number not a string.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage')/1;
Edit: also on the this.val:
$(this).val()/1;
They are probably both strings. You should convert them to numbers first:
var admin = Number($('input[name="diskStorage"]').attr('data-adminstorage')); // 2097152000
$('#new-user input[name="diskStorage"]').keyup(function(){
if(admin < Number($(this).val()))
$(this).css('background','red');
else
$(this).css('background','white');
});

Categories

Resources