<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>
Related
At the moment, I display the amount of characters which are typed into a text box.
I wish to use an alternative display option and show the estimated duration. This means the inputted character amount needs dividing by 15 to give an estimated time (there is roughly 15 characters to 1 second of speech)
How can I add a math calculation to the function below?
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
});
You can add an extra element and use that element to calculate the result of dividing the number of characters from the input with the length method and then dividing by 15. Note I use Math.round() to round the numbers.
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
document.getElementById('duration').innerHTML = Math.round(boxInput.length/15);
});
<form>
<input type="text" id="inputTXT" name="firstname">
<div>
<label>characters: <label id="number">0</label></label>
</div>
<div>
<label>duration: <label id="duration">0</label></label>
</div>
</form>
I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.
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' }">
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.
by default my input value is 1, i want to add +1 each time i click my button. it stops adding when when it reaches 20.
i cant figure out why my code stops at number 3 and just repeats 3.
this is my HTML
<input type="hidden" id="total" value="20" /> //total num
<input type="hidden" id="cur_num" value="1" /> //current num
<button type="button" id="add" >Add</button>
this is javascript and demo here http://jsfiddle.net/zXpen/
$(document).ready(function() {
$(document).on("click", "#add", function() {
cur = $('#cur_num').val();
total = $('#total').val();
console.log(cur);
if (cur <= total) {
cur = parseInt(cur)+parseInt(1);
$('#cur_num').val(cur);
}
});
});
.val() returns a string, so cur <= total is comparing two strings lexicographically, i.e. characters at each position are compared against each other. And "2" in "20" is smaller than "3" in "3".
You have to convert the values to numbers before you compare them, not after that, e.g. by using the unary plus operator. Also don't forget to declare your variables with var:
var cur = +$('#cur_num').val();
var total = +$('#total').val();
You need to convert your values to integers:
cur = parseInt($('#cur_num').val());
total = parseInt($('#total').val());
At the moment your code is comparing "2" <= "20", then "3" <= "20" (as strings). Therefore the if condition is not met and the code within it is not run.
Also, you don't need parseInt(1). cur = parseInt(cur)+1; is fine.