Blank or empty number text box instead of zero value - javascript

I have number text box as shown below.
<input type="number" ng-model="item.TotalUnitsCompleted" />
TotalUnitsCompleted model is an int field.So could you tell me how to set a blank or empty value instead of 0 on the above text box ? At this moment it shows as 0. Thanks in advance.
Note : I don't like to change the int model to string.

You just need to set item.TotalUnitsCompleted = undefined;
If you are using ngTable, just ng-init on each loop ng-init="item.TotalUnitsCompleted = undefined"
Here is an Example:
<input type="number" ng-model="TotalUnitsCompleted" ng-init="TotalUnitsCompleted = initTotalUnits(TotalUnitsCompleted)"/>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.TotalUnitsCompleted = 5;
$scope.initTotalUnits = function(units) {
return (typeof units !== 'undefined' && units > 0 && units !== null) ? units : undefined;
}
});
Plunker

Related

If the value of 'object' is 0 the 'level' input is not displayed

What I have to do is:
When the value of 'object' is 0 the 'level' input is not displayed..
What i have:
input type="text" id="level"
input type="text" id="object"
What i came up with:
var lvl = document.getElementById("level")
var ogg = document.getElementById("object")
if (ogg == 0) {
lvl.style.display = 'none';
};
This is not working and I'm new to JavaScript so please, HELP!!
ogg is just a html node you need to use value property of ogg to access input value
if ( ogg.value == 0) {
lvl.style.display = 'none';
};
Or If you want to check if value is equal to null or blank.
if (!ogg.value && ogg.value.trim() == "") {
lvl.style.display = 'none';
};
You should get the value of the input field using .value attribute like :
if (ogg.value == 0) {
lvl.style.display = 'none';
};
var ogg = document.getElementById("object") gives you element. Use
ogg.value to get the value of input element
Moreover
You get the value as string from input element so
Using == would do what you want but if you really take input as an integer or number you better parse it to int like
var value = parseInt(ogg.value)
And now use it in if condition like
if(value === 0)
Do it this way:
var ogg = document.getElementById("object").value;
.value is used to access the text value from the html element.
Any more questions?
More info:Here
So you can also change the text value of an element with .value
document.getElementById("myOption").value = "newValue";
You have to check the value of object on keyup event. Below is the working sample
var lvl = document.getElementById("level")
var ogg = document.getElementById("object")
function check(){
if (parseInt(ogg.value) === 0) {
lvl.style.display = 'none';
}
else {
lvl.style.display = 'block';
}
}
<input type="text" id="level" placeholder="level">
<input type="text" id="object" placeholder="object" onkeyup="check()">

How to give Amount field placeholder 00.00 which will change as we enter numbers

I am working on project where I have an amount field to enter my requirement is to display placeholder 00.00 and it should change based on the number user enter.
Ex: If I enter 10 the amount field should be 00.10.
Can any one suggest me how to achieve it.
You can do value of text box * 10 + number entered / 100.
Example snippet:
This is just an example, you need to handle keys other than numbers too.
Update: added placeholder:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.formatter = function($event) {
if ($event.which != 8) {
$event.preventDefault();
console.log($event.which)
var temp = $scope.amount || 0;
console.log($event.key);
$scope.amount = (($event.key / 100) + temp * 10).toFixed(2);
} else {
$scope.amount = ($scope.amount / 10).toFixed(3);
$scope.amount = $scope.amount == 0.0 ? undefined : $scope.amount;
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" placeholder="00.00" ng-keypress="formatter($event)" ng-model="amount" />
</div>
Alternatively you can use dir="rtl"
<input placeholder="00.00" id="c" dir="rtl" type="number" step="0.01" max="99.99" min="0">
If you want to have the "." automatically displayed do that in angular.
var input ="00.00";
//get the key press from input, example:3
var keypressed = 3;
var decimalPresision = input.indexOf('.');
console.log('input',input);
var temp1,temp2;
//remove the first digit and split it at '.'
temp1=input.slice(1).split(".");
console.log('temp1',temp1);
//append the keypressed to the last of string and combine the split string
temp2=temp1[0].concat(temp1[1].concat(parseInt(keypressed)));
console.log('temp2',temp2);
//insert the decimal at the marked precesiion and return the result
result=temp2.slice(0,decimalPresision)+"."+temp2.slice(decimalPresision,temp2.length)
console.log('result',result);

How to stop Infinity showing during input

I have created a form which works out a sum depending on the users input, this works fine but during the input stage i get the infinity property displayed in the total. Is there anyway of avoiding this?
I'm by no means a Javascript expecrt so any help would be appreciated. Here is the code.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var third = first / second;
var four = third * 100;
document.getElementById("final").innerHTML = four+"%";
}
</script>
</div><!-- /.wrapper -->
Don't divide by zero.
What you want to do when second is zero is up to you. But probably the easiest way to handle it is to just not do the calculation and not write anything in final unless you have a non-zero value from second.
In addition, you might want to check for NaN as well. If somebody writes a something in either textbox that is not actually a number, you will end up with NaN% in your output. (here you can use isNaN or you can compare the results of parsing your values with NaN).
So you could do something like:
var first = parseFloat(document.getElementsByName("child")[0].value);
var second = parseFloat(document.getElementsByName("parent")[0].value);
if (first !== NaN && second) { // note NaN and 0 are both falsy
// do your calculation here
}
You're going to need to do some validation on your values first. Your calculation only makes sense with numeric values and you're going to have to ensure that you don't try to calculate it if your second variable == 0.
In this case, I wouldn't try to parse/validate the inputs. Do as few as possible, and assume valid inputs.
Just test wether you get a valid output, before showing the result.
function isValidNumber(v){
//!NaN && !Infinity
return v===v && v !== Infinity && v !== -Infinity;
}
//cast the inputs to a valid number
function number(v){
//return +String(v).replace(",", ".");
return +v;
//return +v || 0;
}
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var result = 100 * number(first) / number(second);
document.getElementById("final").innerHTML = isValidNumber(result)?
Math.floor(result) + "%": //I have a valid result
""; //values have changed, but sth. went wrong
}
I think that will work for you.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
if(second == ""){second=1};
if(first != "" && second != ""){
var third = parseInt(first) / parseInt(second);
var four = parseInt(third) * 100;
document.getElementById("final").innerHTML = four+"%";
}
}
</script>
</div><!-- /.wrapper -->
Thanks

Using ng-class with mutiple conditions

I want to set 1 of 3 different classes on a span based on the result of a function. My javascript below seems to be returning the correct value, however my markup is always showing the 'require-matched' class.
How can I write an ng-class directive to accommodate this?
HTML:
<span ng-class="{'require-empty': 0,
'require-matched': 1,
'require-not-matched':2 [form.username.$validators.status]}">
</span>
JS:
ctrl.$validators.status = function (value) {
var expression = /^[-\w]+$/;
if (value != null && value != undefined && value != '' && value != ' ') {
if (expression.test(value))
return 1;
if (!expression.test(value))
return 2;
}
else {
return 0;
}
}
This is incorrect usage of validation in Angular. ctrl.$validators.status should return boolean: true for valid result (required-matched in your terminology) and false otherwise (required-not-match). In case of invalid validation ngModelController will receive boolean flag which you can use in view to style control or show error message.
require-empty that you have should be handled by required validator instead of making status validator do this also.
So what you would probably want to have:
ctrl.$validators.status = function(value) {
if (value) {
var expression = /^[-\w]+$/;
return expression.test(value.trim());
}
return false;
}
or directive can be as concise as
ctrl.$validators.status = function(value) {
return value && /^[-\w]+$/.test(value.trim());
}
Corresponding field in HTML will be (providing that the directive name is status):
<input type="text" name="test" ng-model="testModel" status required>
<div class="error" ng-show="testForm.test.$error.required">The field is required.</div>
<div class="error" ng-show="testForm.test.$error.status">The value should match pattern.</div>
Demo: http://plnkr.co/edit/YALB4Vbi5FzNH5FCfwB5?p=preview

How to restrict Textbox value with the max value on key events?

I have a text box i want to restrict that value for max value using key events
I try with the below code and its work fine
function validateRange(ele) {
if(ele.val() < 0 || ele.val() > 100){
console.log('false');
}else{
console.log('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});
HTML:
<form:input type="text" path="depth" cssClass="number inplace-textbox digit-validation" data-min="0" size="10" />
I would like if(ele.val() < 0 || ele.val() > 100) is stop keypress.
Update: I am trying to do range of values validation.
I'd suggest that you try and use the HTML5 input type of number, with min and max attributes:
<input type="number" min="0" max="100" />
JS Fiddle demo.
This allows the user to enter a number directly (using the keyboard, or copy/paste), and allows for control of the increments using the step attribute (step="2", for example, will allow increments, or decrements, of 2 on every click of the spinner arrows).
If, however, you must use a non-number input:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.digit-validation').keydown(function(event){
var v = parseFloat(this.value + String.fromCharCode(event.which));
return parseFloat(v).between(0,100,true);
});
JS Fiddle demo.
Why do you not use maxlength HTML attribute ?
<input type="text" maxlength="100" />
There is no need to use JS to achieve this.
For your validation, you need 2 things :
check if the user enters a number
check if the user enters something between 0 and 100
For the 1st one, since you use jQuery, you can use $.isNumeric().
For the 2nd one, you need to parse the value as integer thanks to parseInt().
That would give you :
http://jsfiddle.net/tLwYX/
function validateRange(ele) {
var val = ele.val();
if(!$.isNumeric(val) || parseInt(val,10) < 0 || parseInt(val,10) > 100){
$('#result').html('false');
}else{
$('#result').html('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});

Categories

Resources