ng-change on number input for validation - javascript

I have a number input where I set the min and max dynamically based on another form field. My scenarios are as follows:
Level 1: Min = 2, Max = 50
Level 2: Min = 5, Max = 1000
I have a ng-change event set up on the input field, to evaluate if the number follows my rules for each level. If the number is either too high or too low, I set it to the minimum.
<input type="number" step="1" ng-change="isValid()" ng-model="level.num" min="{{minNum}}" max="{{maxNum}}">
$scope.isValid = function () {
if( ($scope.level.num > $scope.maxNum) || ($scope.level.nums < $scope.minNum)) {
$scope.tooMany = true;
$scope.level.num = $scope.minNum;
}
};
My Problem is that lets say I have selected Level 1 and want to enter 15, as soon as I enter 1 it automatically changes my number to 2. How can I only change the number when the user has full finished entering their input.

My idea is to apply blur as your change factor for min-number enforcment, because it's can be a standard usecase if your min-set is 3 and the input is 24 etc. this way you can encapsulate in 1 function and still maintain the logic
<input type="number" step="1" ng-blur="isValid(true)" ng-change="isValid(false)" ng-model="level.num" min="{{minNum}}" max="{{maxNum}}">
$scope.isValid = function (blurMode) {
if( ($scope.level.num > $scope.maxNum) || ($scope.level.nums < $scope.minNum && blurMode)) {
$scope.tooMany = true;
$scope.level.num = $scope.minNum;
}
};

if you are using angular 1.3 maybe you can use ng-model-options: example
<input type="text" ng-model="name" ng-model-options="{ updateOn: 'blur' }">

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Calculate discount using jquery

I am calculating Discount using jquery. But I have a problem calculating the correct discount. My calculation gives me wrong result.
Here is my code
$(document).on("change keyup blur", "#chDiscount", function() {
var amd = $('#cBalance').val();
var disc = $('#chDiscount').val();
if (disc != '' && amd != '')
$('#cBalance').val((parseInt(amd)) - (parseInt(disc)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">
I have a prepopulated value for cBalance input i.e.,1575. When I type discount value for example 500 in chDiscount input, it gives me 1020 and not 1075. And I want the value 1575 to be 1575 when there is no value or zero value in the chDiscount input. And the caculation keeps incrementing the cBalance value whenever I type new value in the chDiscount input, it does not increment from the default value.
My exptected output: When I type 500, I want the default value 1575 to be 1075. And if I delete the 1000 that I type, I want back the default value 1575 in cBalance. And If I type 5 in chDiscount, the default value would become 1570 and if I hit backspace to delete, it would become 1575 again.
How can I achieve this? Where did I go wrong? Please help.
$(document).on("change keyup blur", "#chDiscount", function() {
var amd = $('#cBalance').val();
var disc = $('#chDiscount').val();
if (disc != '' && amd != '') {
$('#result').val((parseInt(amd)) - (parseInt(disc)));
}else{
$('#result').val(parseInt(amd));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">
<br>
<input type="number" id="result">
I added result field because otherwise you couldn't specify amd
As above mention code is just subtracting the main value. here is exact solution
<input type="number" id="cBalance" value="1575"> <br>
<input type="number" id="chDiscount"> <br>
<input type="number" id="result">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$(document).on("change keyup blur", "#chDiscount", function() {
var main = $('#cBalance').val();
var disc = $('#chDiscount').val();
var dec = (disc/100).toFixed(2); //its convert 10 into 0.10
var mult = main*dec; // gives the value for subtract from main value
var discont = main-mult;
$('#result').val(discont);
});
JSFIDDLE

Angularjs Price slider is going out of range when ng-model is null or less than minimum value

I have an rz-slider on my page. It is used for getting the price of a product from user. Along with the slider I have two input fields, which is used to store the min and max values. the ng-model for the min and max input fields are same as the rz-slider-model and rz-slider-high respectively.
The problem is, when ever I change the min or max input field to 0 the slider is going out of range. Is there any way to limit my slider in the specified range?
<input type="number" min="1000" max="5000" ng-model= "priceSlider.min"> to
<input type="number" min="1000" max="5000" ng-model= "priceSlider.max">
<rzslider
rz-slider-floor="priceSlider.floor"
rz-slider-ceil="priceSlider.ceil"
rz-slider-model="priceSlider.min"
rz-slider-high="priceSlider.max"
rz-slider-step="{{priceSlider.step}}"></rzslider>
See my Plunk for reference.
You can use ng-change directive of angularjs to validate value of min and max.
<input type="number" min="1000" max="5000" ng-change="checkMin()" ng-model= "priceSlider.min"> to
<input type="number" min="1000" max="5000" ng-change="checkMax()" ng-model= "priceSlider.max">
Controller:
$scope.checkMin = function() {
if (typeof $scope.priceSlider.min === 'undefined' || $scope.priceSlider.min < 1000 || $scope.priceSlider.min > 5000) {
$scope.priceSlider.min = 1000;
}
}
$scope.checkMax = function() {
if (typeof $scope.priceSlider.max === 'undefined' || $scope.priceSlider.max < 1000 || $scope.priceSlider.max > 5000) {
$scope.priceSlider.max = 5000;
}
}
This option doesn't allow set value by text to say 3000 because when user edit input box, ng-change function called and if value is not in range then set to default value.
Check plunkr for details.
Other option
Use ng-blur but the issue with ng-blur is if user enter 0 then it allows to set that value and on blur event it set value to default if input is not in valid range.
Choose appropriate based on requirement.

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Decrease variable by 1 Javascript

<input type='text' maxlength='32' onkeypress='previewLength(32)'>
I want to decrease 32 with 1 each time a key is pressed
Im using this for a length preview (max length is 32 and each time a key is pressed it gets decreased by 1 and shows the user how much he has left)
<script>
function previewLength (maxLength) {
maxLength = maxLength -= 1;
document.getElementById('CounterLength').innerHTML = maxLength;
}
</script>
Use the length of the actual value instead of counting keypresses (as for example the backspace key would reduce the length instead of increasing it):
<input type="text" maxlength="32" onkeypress="previewLength(this.maxLength, this.value.length, 'CounterLength');">
<script type="text/javascript">
function previewLength (maxLength, actualLength, id) {
document.getElementById(id).innerHTML = maxLength - actualLength;
}
</script>
(By also sending the maxlength and display element id into the function, it can be reused for multiple elements.)
You have some misconceptions, you'll want to look at the actual value, not the number of keypresses. For example: backspace, and arrow-left are also keypresses but they don't increase the length of the value.
html:
<input type='text' maxlength='32' onkeypress='previewLength(this, 32)'>
^- use `this`
js:
function previewLength (input_element, maxLength) {
var remain = maxLength - input_element.value.length;
document.getElementById('CounterLength').innerHTML = remain;
}
I would add some check not to show negative number, and just pass name of the control
window.updateCounter = function updateCounter(e, name) {
var len = e.value.length
, max = e.maxLength
, remaining = (max - len) > 0 ? max-len : 0
document.getElementById(name).innerHTML = remaining
}
markup
<input type='text' maxlength='32' onkeypress='updateCounter(this, "counter")'/>
<span id='counter'>32</span>

Categories