I have an input and I need it to be limited to only these values:
Min: 0.01 max 999.99
If I use maxlength="6" I can enter, for instance, 999.99 but also 1000.1 which is not an accepted value.
What I've tried:
1st attempt (not working):
<input type="number" id="quantity" name="quantity" maxlength="6" min="0.01" max="999.99">
2nd attempt (partially working):
let maximumFractionDigits = 2;
const formatNumber = (value) => {
return parseFloat(value.replace(/,/g,'')).toLocaleString('en-US', { maximumFractionDigits });
}
$('input[name="test"]').on('keyup',function(){
maximumFractionDigits = 2;
if (!$(this).val() || (maximumFractionDigits && $(this).val().endsWith('.'))) {
return
}
$(this).val(formatNumber($(this).val()).replace(/,/g,''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
INPUT TEST
<input type="text" maxlength="6" name="test" class="form-control">
<br>
With the second approach, I still can input weird numbers like 10000. and values like 0.0X can't be introduced (I guess it's rounded), how could I just limit the values to Min: 0.01 max 999.99?
You can check for 3 conditions,
For first 2 convert number to string
The max length of the string should be 6
maxlength = 6
If string has decimal point then .split('.') and check the length of decimal numbers
const decimal = input.split('.')[1]
Check if the number is
0.01 < number < 999.99
You have to methods to achieve the same
change the input type, and set min-max values:
<input type="number" min=0.01 max=999.99 name="test" class="form-control" aria-label="Equipment Procurement %">
If you don't want to change the type:
const numInput = document.querySelector(".form-control");
numInput.addEventListener("input", (event) => {
const number = parseInt(e.target.value);
if (number > 999.99 && number < 0.01) // throw Error or do whatever you want to do
})
So basically I found a solution:
const input = document.querySelector('.example');
input.addEventListener('input', updateValue);
function updateValue(e) {
let number = e.target.value;
number = number.toString();
if(number.match(/^\d{1,3}(\.\d{1,2})?$/)){
console.log("True");
} else{
const newNum = (e.target.value).toString().slice(0, -1)
e.target.value = parseFloat(newNum);
}
}
<input type="number" class="form-control example" id="quantity" name="quantity" maxlength="6" min=0.01 max=999.99>
Hope this helps if someone has the same situation
Related
I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
i have multiple input number fields with the same class, and i have to sum them but when I try with my javascript i get always NaN result
var arrNumber = new Array(); //contain the number of specific input field
var totale;
$(".input-n-pro").bind('keyup mouseup', function () {
totale = 0;
$('.input-n-pro').each(function(){
var this_num = $(this).val();
totale = parseInt(this_num)+parseInt(totale);
})
console.log("totale="+totale);
});
The html of input is this, generated by php, one for every row of a table
<input type="number" name="<?php echo $data["name"];?>" min="0" max="500" placeholder="0" class="form-control input-xs input-n-pro" style="display: inline">
I don't know it won't work, it work with only js withous jquery but i have to get the id of every field to do that and i want to do that for everyone with the same class because they are dinamic fields
P.S. The other part of my work, is to get every name of those fields and store them so i can have an array in js where i have the name of input and his number value, but i don't know how to do because they are dinamic
You probably parsing something that is not an integer. Then the parseInt won't work and returns NaN. If you sum a NaN, then it stays a NaN, example:
// working testcase:
const testArray = ['2', '3', '4'];
let total = 0;
for (value of testArray) {
total += parseInt(value);
}
// returns 9
console.log(total);
// your testcase:
const testArray2 = ['2', '3', 'notANumber'];
let total2 = 0;
for (value of testArray2) {
total2 += parseInt(value);
}
// returns NaN since we are adding 2 + 3 + NaN = NaN
console.log(total2);
So the solution is to 'negate' the NaN by treating it as 0:
// solution:
const myArray = ['2', '3', 'notANumber', '4'];
let total = 0;
for (value of myArray) {
// treat NaN, undefined or any falsey values as 0.
total += parseInt(value) || 0;
}
// returns 9
console.log(total);
To integrate this concept in your code, you'll get something like:
let total = 0;
$('.input-n-pro').each(() => {
let valueInString = $(this).val();
let actualValue = parseInt(valueInString) || 0;
total += actualValue;
});
if one of inputs value is empty then parseInt returns NAN. So you can better do a check using IsNan function. if input is empty than assign 0. For example;
var x= parseInt($('#abc').val()); if (isNaN(x)) x = 0;
Part 1 and 2 of your question
The reason you get NaN is most probably that if any of the inputs has no value, asking for that value returns an empty string (form fields always return strings) "". parseInt("") returns NaN.
Using vanilla ECMAScript 6, the solution is a one-liner with the help of Array.prototype.reduce:
const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0);
For your second question, just use Array.prototype.map. Also a one-liner.
const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }});
Note: The Array spread operator [...document.querySelectorAll('.input-n-pro')] makes an array from the NodeList document.querySelectorAll returns, so you can use Array methods on the list (like reduce and map).
Example:
calc.addEventListener('click', () => {
const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0);
console.log(sum);
})
getArr.addEventListener('click', () => {
const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }});
console.log(theArr);
})
<input type="number" value="5" class="input-n-pro" name="a" />
<input type="number" value="3" class="input-n-pro" name="b" />
<!-- lets insert one input that contains no number -->
<input type="text" value="foo" class="input-n-pro" name="m" />
<input type="number" value="2" class="input-n-pro" name="c" />
<input type="number" value="11" class="input-n-pro" name="d" />
<input type="number" class="input-n-pro" name="e" />
<br />
<button id="calc" type="button">Calculate Sum</button>
<button id="getArr" type="button">Get Array of name-value pairs</button>
bind() has been deprecated => use on
arrNumber = [], //contain the number of specific input field
totale = 0;
doTotale(); // first round
$(".input-n-pro").on('keyup mouseup change', doTotale);
function doTotale()
{
totale = 0;
arrNumber.length = 0;
$('.input-n-pro').each(function()
{
let
name = $(this).attr('name'),
val = parseInt($(this).val(),10) || 0;
arrNumber.push( {name, val });
totale += val;
})
console.clear();
console.log("totale =",totale);
console.log("arrNumber =", JSON.stringify(arrNumber) );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
AA : <input type="number" name="AA" value="5" class="input-n-pro" /> <br>
BB : <input type="number" name="BB" value="3" class="input-n-pro" /> <br>
CC : <input type="text" name="CC" value="foo" class="input-n-pro" /> <br> <!-- lets insert one input that contains no number -->
DD : <input type="number" name="DD" value="2" class="input-n-pro" /> <br>
EE : <input type="number" name="EE" value="11" class="input-n-pro" /> <br>
FF : <input type="number" name="FF" class="input-n-pro" />
My goal is to limit the number of digit user can enter in the input field. So a user can only input 10 digits. I tried min and max still doesn't work
Here's the code
<input
v-model="amount"
type="number"
>
<script>
export default {
data() {
return {
amount: 7800
}
}
}
</script>
Right now i can add more than 10 digits
Replace this:
<input v-model="amount" type="number">
to
<input v-model="amount"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "10"
/>
We can control the value of <input> manually:
<input
type="number"
:value="amount"
#input="updateValue"
/>
and check in updateValue method:
data() {
return {
amount: 7800
}
},
methods: {
updateValue(event) {
const value = event.target.value
console.log(value, this.amount)
if (String(value).length <= 10) {
this.amount = value
}
this.$forceUpdate()
}
}
Note that this.$forceUpdate() is used to make component re-render when user input more than 10 characters.
Demo on Codepen
Put a condition on Updated, checking the digits, if surpasses it, cut it. I did something similar, but for max value, not digits, but i think its the same logic:
updated() {
if (this.album.max_colorized > this.maxPictures) {
this.album.max_colorized = this.maxPictures;
}
}
This way if it surpasses the max, change to max.
I am trying to add a text box which accepts only integers between 1 and 99. I tried adding a number type element with min and max but that works only when changing the number using the ticker
<input type="number" min="1" max="99" />
May I know a better way to achieve this?
UPDATE:
I would like to immediately validate the input like may be by replacing the entry with an empty character.
You can use JavaScript to validate the input on a key event (such as keyup). Here's an example that will clear out anything that's not an integer between 1 and 99.
var inputBox = document.getElementById('inputBox');
inputBox.addEventListener('keyup', function(e) {
inputBox.value = "" + inputBox.value;
if (e.which < 48 || e.which > 57) {
// if not an integer
clearInput();
return;
}
if (inputBox.value.toLowerCase() !== inputBox.value.toUpperCase()) {
// if a letter
clearInput();
return;
}
if (parseInt(inputBox.value) < 1 || parseInt(inputBox.value) > 99) {
// if value is not in the desired range
clearInput();
return;
}
});
function clearInput() {
// invalid entry -- clear out input box
inputBox.value = "";
}
inputBox.focus(); // this is just for ease of testing
<input id="inputBox" type="number" min="1" max="99" />
How about this? This shouldn't allow for negative numbers, and you're restricted to only 2 characters.
<input type="number" min="1" max="99" maxlength="2" />
I am fairly new to javascript. Building a custom javascript calculator to set pricing for some products. There is sometimes a fee that is added. This fee is either a percentage of cost or an actual dollar amount. If it is a percentage, it will have a percentage sign. After researching, came up with the following solution that works only if a dollar amount is entered but not if percentage is entered. Is there a better solution?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
Because you are converting the input to a number with:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
Any symbols will cause that conversion to fail and therefore you wouldn't be able to perform your test.
var num = Number("234.50%");
console.log(num); // Not a Number
Instead, before doing the conversion, just simply test for the presence of the symbol with .indexOf which returns -1 when the test can't find a match.
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<input type="text" id="num1">
Having said all of that, I agree with the comments that a better way to handle this is by not asking the user to input the unit at all and just provide radio buttons:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>