Dividing thousands number for the field - html

When I'm texting the number in my text (or number) field I need the number to be divided by thousands with a comma.
Example
1. instead of it saying “1000” make it say “1,000”.
2. “1000000” make it say “1,000,000”.

Using Script
$(document).on('keyup', '.Amount', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
Live Demo Here
Snippet Example Below
$(document).on('keyup', '.Amount', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Enter Amount:<input class="Amount" type="Amount" />
</form>

This could help you
window.onload=function(){
var numberinput=document.getElementById('number');
numberinput.addEventListener('change',changedValue);
}
function changedValue(){
var input=this.value
var number=parseInt(input,10);
if(number>=1000)
{
var numbersArray = input.toString().split(".");
numbersArray[0] = numbersArray[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
this.value= numbersArray.join(".");
}
}
<input type="text" id="number" >
Hope this helps

$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
JS Fiddle

Related

Limit number of characters in input where jquery numpad is used

How would I limit number of characters in input where jquery keypad is used?
HTML
<input id="num-input" type="text" maxlength="3" disabled>
JQUERY
var $numInput;
$(function() {
initKeyboard($('#numeric-keyboard'), $('#num-input'));
$('#num-input').on('keydown', function(e) {
$('#event').text('key: '+e.keyCode);
});
$('#back').on('click', onBackBtn);
$('#forward').on('click', onForwardBtn);
});
function onBackBtn() {
$('input').first().focus();
}
function onForwardBtn() {
$('input').last().focus();
}
function initKeyboard($keyboard, $input) {
$numInput = $input;
$keyboard.on('click', '.key', onKeyPress);
}
function onKeyPress(e) {
var keyValue = $(this).text();
if(keyValue.toLowerCase() === 'delete') {
keyValue = 8;
} else if(keyValue === '') {
return;
} else {
keyValue = keyValue.charCodeAt(0);
}
var e = $.Event("keydown");
e.which = keyValue;
e.keyCode = keyValue;
$numInput.trigger(e);
if(keyValue !== 8) {
$numInput.val( $numInput.val() + $(this).text() );
} else {
$numInput.val( $numInput.val().slice(0, -1) );
}
}
maxlenght is ignorred, I attempted to add if clause to $numInput.val( $numInput.val() + $(this).text() ); this part of the code with var max=3; but again no luck.
I have also tried with out of this code script to limit number of characters for that input but again jquery overtakes it and keep adding characters.
I need t set limit of 3 characters to it.
Any idea?
#num-input is disabled, maybe maxlength need to be set in #numeric-keyboard field?

html type="number" : Show always 2 digits after dot?

in a type="number" input, i would like to show 2 digits after dot like "2.50"
if a try
<input name="price" type="number" step="0.01" value="2.5">
this show me "2.5" and not "2.50"
Have you a method to do this ? HTML5 pure or with javascript ?
you need to use Jquery or JavaScript for that what ever you want but this solution in Jquery
You Can't go for more than 2 number
//Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows
$('.trailing-decimal-input').on('keyup mouseup', function (e) {
// on keyup check for backspace & delete, to allow user to clear the input as required
var key = e.keyCode || e.charCode;
if (key == 8 || key == 46) {
return false;
};
// get the current input value
let correctValue = $(this).val().toString();
//if there is no decimal places add trailing zeros
if (correctValue.indexOf('.') === -1) {
correctValue += '.00';
}
else {
//if there is only one number after the decimal add a trailing zero
if (correctValue.toString().split(".")[1].length === 1) {
correctValue += '0'
}
//if there is more than 2 decimal places round backdown to 2
if (correctValue.toString().split(".")[1].length > 2) {
correctValue = parseFloat($(this).val()).toFixed(2).toString();
}
}
//update the value of the input with our conditions
$(this).val(correctValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="2.50" />
you can preview or edit code Here on JSFiddle
You can solve by script Like :
<script type="text/javascript">
$(document).ready(function() {
var num = 2.5;
var n = num.toFixed(2);
alert(n);
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var num = 2.500;
var n = num.toFixed(1);
alert(n);
});
</script>

Javascript how to allow array to take more than one digit?

I've been trying lately to build up a mean calculator using html and javascript. i want to take all the inputs from the one text box add them to an array and get the average result. what i did in the following code takes only one digit because of str[i-1] is there any other alternative way of doing it? Thanks!
Output photo
function calculate()
{
var str= document.getElementById("meanvalue").value;
for(var i=0; i<str.length; i++)
{
if(str[i] == ".")
{
sum+=parseInt(str[i-1]);
count++;
}
}
sum/=count;
document.getElementById("meanresult").value=sum;
}
Here is a small example:
document.getElementById('input').onkeyup = function() {
this.value = this.value.replace(/[^0-9\.]/gi, '');// restrict non digit
var sum = 0;
var array = this.value.split(/\./);
array.forEach(function(str) {
sum += (parseInt(str, 10) || 0); //avoid NaN
});
document.getElementById('output').value = (sum / array.length || 0);// avoid NaN
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
i just want to know how the values are updated while im typing my
inputs automatically
Here, I am using onkeyup event to handle user input.
document.getElementById('input').onkeyup = function() {
document.getElementById('output').value = this.value;//get input, set output
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
You can use the split function on the input. I give you a quick example here :
var string = "1.3.45.7";
var array = string.split(".");
// array = [1, 3, 45, 7]
document.write(array);
First split your str and than use for loop.
var str= document.getElementById("meanvalue").value.split('.');
Also remove your if condition inside the loop.
for(var i=0; i<str.length; i++)
{
//if(str[i] == ".")
// {
sum+=parseInt(str[i-1]);`
count++;
// }
}
sum/=count;
document.getElementById("meanresult").value=sum;
hope this helps you.

HTML number input min and max not working properly

I have type=number input field and I have set min and max values for it:
<input type="number" min="0" max="23" value="14">
When I change the time in the rendered UI using the little arrows on the right-hand side of the input field, everything works properly - I cannot go either above 23 or below 0. However, when I enter the numbers manually (using the keyboard), then neither of the restrictions has effect.
Is there a way to prevent anybody from entering whatever number they want?
Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript
With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
In some cases pattern can be used instead of min and max. It works correctly with required.
Despite the HTML5 enforcement of min and max on the up/down arrows of type=number control, to really make those values useful you still have to use Javascript.
Just save this function somewhere and call it on keyup for the input.
function enforceMinMax(el) {
if (el.value != "") {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
<input type="number" min="0" max="23" value="14" onkeyup=enforceMinMax(this)>
<input type="number" min="0" onkeyup="if(value<0) value=0;" />
$(document).ready(function(){
$('input[type="number"]').on('keyup',function(){
v = parseInt($(this).val());
min = parseInt($(this).attr('min'));
max = parseInt($(this).attr('max'));
/*if (v < min){
$(this).val(min);
} else */if (v > max){
$(this).val(max);
}
})
})
Here is my contribution. Note that the v < min is commented out because I'm using Bootstrap which kindly points out to the user that the range is outside the 1-100 but wierdly doesn't highlight > max!
oninput="if(this.value>your_max_number)this.value=your_max_number;"
This works properly for me.
One event listener, No data- attribute.
You can simply prevent it by using following script:
$(document).on('keyup', 'input[name=quantity]', function() {
var _this = $(this);
var min = parseInt(_this.attr('min')) || 1; // if min attribute is not defined, 1 is default
var max = parseInt(_this.attr('max')) || 100; // if max attribute is not defined, 100 is default
var val = parseInt(_this.val()) || (min - 1); // if input char is not a number the value will be (min - 1) so first condition will be true
if (val < min)
_this.val(min);
if (val > max)
_this.val(max);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="form-control" name="quantity" max="250" min="1" value="">
The only problem is: You can't type - to get negative numbers if your min is lower than 0
This works for me I think you should try this you change the pattern according to your need
like you start from pattern 1
<input type="number" pattern="[0-9]{2}" min="0" max="23" value="14">
You can use html keyup event for restriction
<input type="number" min="0" max="23" value="14" onkeyup="if(value<0) value=0;if(value>23) value=23;">
Use this range method instead of number method.
$(function () {
$("#input").change(function () {
// Save old value.
$("#limit").val($("#input").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="limit" name="limit" value="14" readonly><br>
<input type="range" id="input" name="input" min="0" max="23" value="14"/>
Forget the keydown or keyup: it won't let you enter like 15 or 20 if the min was set to 10!
Use the change event since this is where the input value goes in your business logic (ViewModel):
private _enforceMinMax = (input:HTMLInputElement) => {
console.log("input", input);
const v = parseFloat(input.value);
if(input.hasAttribute("min")) {
const min = parseFloat(input.min);
if(v < min) {
input.value = min+"";
}
}
if(input.hasAttribute("max")) {
const max = parseFloat(input.max);
if(v > max) {
input.value = max+"";
}
}
}
private _distanceChange = (event) => {
this._enforceMinMax(event.target);
...
$(document).on('keyup', 'input[type=number][min],input[type=number][max]', function () {
var _this = $(this);
if (_this.val() === "-")
return;
var val = parseFloat(_this.val());
if (_this.attr("min") !== undefined && _this.attr("min") !== "") {
var min = parseFloat(_this.attr('min'));
if (val < min)
_this.val(min);
}
if (_this.attr("max") !== undefined && _this.attr("max") !== "") {
var max = parseFloat(_this.attr('max'));
if (val > max)
_this.val(max);
}
});
$(document).on('change', 'input[type=number][step]', function () {
var _this = $(this);
var val = parseFloat(_this.val());
if (_this.attr("step") !== undefined && _this.attr("step") !== "") {
var step = parseFloat(_this.attr('step'));
if ((val % step) != 0)
_this.val(val - (val % step));
}
});
This work perfect for geographic coordinates when you have general function document EventListener "keydown" in my example i use bootstrap class.
<input type="text" name="X_pos" id="X_pos" class="form-control form-control-line" onkeydown="event.stopPropagation(); return(parseInt(event.key) >= 0 && parseInt(event.key) <= 9 && this.value+''+event.key <= 179 && this.value+''+event.key >= (-179)) || this.value.slice(-1) == '.' && parseInt(event.key) >= 0 && parseInt(event.key) <= 9 || event.keyCode == 8 || event.keyCode == 190 && String(this.value+''+event.key).match(/\./g).length <=1 || event.keyCode == 109 && String(this.value+''+event.key).length == 1 || event.keyCode == 189 && String(this.value+''+event.key).length == 1" style="width:100%;" placeholder="X" autocomplete="off">
If you want you can create a function with this code but i preferred this method.
Again, no solution truly solved my question. But combined the knowledge, it somehow worked
What I wanted is a true max/min validator (supporting int/float) for my input control without fancy html5 help
Accepted answer of #Praveen Kumar Purushothaman worked but its hardcoded min/max in the checking condition
#Vincent can help me dynamically validate the input field by max/min attributes but it is not generic and only validating the integer input.
To combine both answer
Below code works for me
function enforceMinMax(el){
if(el.value != ""){
if(parseFloat(el.value) < parseFloat(el.min)){
el.value = el.min;
}
if(parseFloat(el.value) > parseFloat(el.max)){
el.value = el.max;
}
}
}
$(function () {
$("input").keydown(function () {
enforceMinMax(this);
});
$("input").keyup(function () {
enforceMinMax(this);
});
});
For the DOM
<input type="number" min="0" max="1" step=".001" class="form-control">
Afterwards all my inputs are truly responsive on the min max attributes.
Solution to respect min and max if they are defined on an input type=number:
$(document).on("change","input[type=number][min!=undefined]",function(){if($(this).val()<$(this).attr("min")) $(this).val($(this).attr("min"))})
$(document).on("change","input[type=number][max!=undefined]",function(){if($(this).val()>$(this).attr("max")) $(this).val($(this).attr("max"))})
Here is my Vanilla JS approach of testing against the set min and max values of a given input element if they are set.
All input.check elements are included in the input check. The actual input check is triggered by the change event and not by keyup or keydown. This will give the user the opportunity to edit their number in their own time without undue interference.
const inps=document.querySelectorAll("input.check");
inps.forEach(inp=>{
// memorize existing input value (do once at startup)
inp.dataset.old=inp.value;
// Carry out checks only after input field is changed (=looses focus)
inp.addEventListener("change",()=>{
let v=+inp.value;
// console.log(v,inp.min,inp.max,inp.dataset.old);
if(inp.max!=""&&v>+inp.max || inp.min!=""&&v<+inp.min) inp.value=inp.dataset.old;
else inp.dataset.old=inp.value;
});
})
<input class="check" type="number" min="0.1" max="23.4" value="14" />
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
You can compare keyCode and return false if those keys aren't numbers
for e.g
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script>
function handleKeyDown(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="number" min="0" max="23" value="14" onkeydown="handleKeyDown(event)" />
</body>
</html>
if you still looking for the answer you can use input type="number".
min max work if it set in that order:
1-name
2-maxlength
3-size
4-min
5-max
just copy it
<input name="X" maxlength="3" size="2" min="1" max="100" type="number" />
when you enter the numbers/letters manually (using the keyboard), and submit a little message will appear in case of letters "please enter a number" in case of a number out of tha range "please select a value that is no more/less than .."

I need with parsing an array from google script to HTML

I have a date picker that I'd like to use to choose an event and then show details from a spread sheet.
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function(date) {
var stuff= updDate(date);
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1,
});
});
</script>
<script>
function updDate(date){
google.script.run.updDate(date);
}
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" onchange="updDate()"></p>
Hello, world!
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
</html>
Google Script:
function updDate(date){
var searchString = date;
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var s2 = SpreadsheetApp.openById("*************");
var row = new Array();
var k;
for (var i in data) {
//Logger.log("length is: "+data[i].length)
//var p = data[i].length
for (var j in data[i]) {
//Logger.log("We are at i: "+i) //Row
//Logger.log("We are at j: "+j) //Col
if (i !=0){
if(data[i][j] != ""){
if(j == 4){
//Logger.log("date from picker: " + date);
//Logger.log("date from Data: " + data[i][j]);
var ssDate = Utilities.formatDate(data[i][j], "GMT", "MM/dd/yyyy");
//Logger.log("date post Convert: " +ssDate);
if(date == ssDate){
k= i
var p = data[i].length
Logger.log("P is: " +p);
}
}
}
}
}
}
Logger.log("K is: "+k)
var q = 1
while (q <= p){
row[q] = data[k][q];
q++
}
Logger.log("Row: " +row);
return row;
}
Eventually I'd like to get the data read into a table but I've been hitting a wall when it comes to successfully getting the data read into a variable in the HTML.
Right now I get this error:
Uncaught ScriptError: The script completed but the returned value is not a supported return type.
Any help in returning the array "row"(in the google script) to the variable "stuff"(in the HTML) successfully or any pointers about how to better execute this task would be greatly appreciated.
Loren
Edit code:
function updDate(date){
var stuff = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
Console.log(stuff)
}
function myReturnFunction(){
window.myReturnFunction = function(whatGotReturned) {console.log(whatGotReturned);};
}
Sandy Good had it right in the comments above:
function updDate(date){
var junk = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
}
function myReturnFunction(whatGotReturned){
console.log(whatGotReturned);
}