For example i have a textbox, I am entering 12000 and i want it to look like 12,000 in the textbox How would I do this? Im using html to do the textbox
Try something like this
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Then use it on your textboxes like so
<input type="text" id="txtBox" onchange="return addCommas(this.value)" />
Hope that helps
Use the jQuery autoNumeric plugin:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Input with separator</title>
<script type="text/javascript" src="jquery-1.11.0.js"></script>
<script type="text/javascript" src="autoNumeric.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$("#myinput").autoNumeric(
'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'}
);
});
</script>
</head>
<body>
<input id="myinput" name="myinput" type="text" />
</body>
</html>
This is probably a bad idea...
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Comma Thousands Input</title>
<style>
label, input, button{font-size:1.25em}
</style>
<script>
// insert commas as thousands separators
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
// return integers and decimal numbers from input
// optionally truncates decimals- does not 'round' input
function validDigits(n, dec){
n= n.replace(/[^\d\.]+/g, '');
var ax1= n.indexOf('.'), ax2= -1;
if(ax1!= -1){
++ax1;
ax2= n.indexOf('.', ax1);
if(ax2> ax1) n= n.substring(0, ax2);
if(typeof dec=== 'number') n= n.substring(0, ax1+dec);
}
return n;
}
window.onload= function(){
var n1= document.getElementById('number1'),
n2= document.getElementById('number2');
n1.value=n2.value='';
n1.onkeyup= n1.onchange=n2.onkeyup=n2.onchange= function(e){
e=e|| window.event;
var who=e.target || e.srcElement,temp;
if(who.id==='number2') temp= validDigits(who.value,2);
else temp= validDigits(who.value);
who.value= addCommas(temp);
}
n1.onblur= n2.onblur= function(){
var temp=parseFloat(validDigits(n1.value)),
temp2=parseFloat(validDigits(n2.value));
if(temp)n1.value=addCommas(temp);
if(temp2)n2.value=addCommas(temp2.toFixed(2));
}
}
</script>
</head>
<body>
<h1>Input Thousands Commas</h1>
<div>
<p>
<label> Any number <input id="number1" value=""></label>
<label>2 decimal places <input id="number2" value=""></label>
</p></div>
</body>
</html>
You can use the Javascript Mask API
You can try this simple Javascript
<script type="text/javascript">
function addcommas(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
HTML Code
<div class="form-group">
<label>Amount </label>
<input type="text" name="amount" onkeyup="this.value=addcommas(this.value);"class="form-control" required="">
</div>
For user input I would recommend not formatting the value to include a comma. It will be much easier to deal with an integer value (12000), than a string value (12,000) once submitted.
However if you are certain on formatting the value, then as #achusonline has recommended, I would mask the value. Here is a jQuery plugin which would be useful to get this result:
http://digitalbush.com/projects/masked-input-plugin/
adding punctuation or commas of numbers on input change.
html code
<input type="text" onkeyup="this.value=addPunctuationToNumbers(this.value)">
Javascript Code
<script>
function addPunctuationToNumbers(number) {
return number.replace(/(\d{3})(?=\d)/g, "$1,");
}
</script>
<!DOCTYPE html>
<html>
<body>
<h1>On change add pumctuation to numbers</h1>
<input type="text" onkeyup="this.value=addPunctuationToNumbers(this.value)">
<script>
function addPunctuationToNumbers(number) {
return number.replace(/(\d{3})(?=\d)/g, "$1,");
}
</script>
</body>
</html>
You can use very handy JavaScript method, called Intl.NumberFormat:
<script>
//Value formatting
document.getElementById('your-input-id').addEventListener('change', function(event) {
//Check for specific CSS class of your input first
if (event.target.classList.contains('some-css-class')) {
// remove any commas from earlier formatting
const value = event.target.value.replace(/,/g, '');
// try to convert to an integer
const parsed = parseInt(value);
//NumberFormat options
const options = {
style: 'decimal',
maximumFractionDigits: 10,
useGrouping: true,
maximumSignificantDigits: 20,
};
// check if the integer conversion worked and matches the expected value
if (!isNaN(parsed) && parsed == value) {
// update the value
event.target.value = new Intl.NumberFormat('en-GB', options).format(value);
}
}
});
</script>
Related
I am pretty bad at JS but I need some help at a task in order to prepare for a small exam on web technology.
The task:
I have to write a code where two input fields have to be displayed. The sum of both of the input fields have to be 100. So the input fields will be mainly used for typing in some numbers.
When I type a number in the first input field between 0 - 100 there should be displayed the remaining amount of 100 in the second input field after typing the last number of the first number. This should be also working vice versa. So it should be irrelevant which input field I type in the number. Our professor suggests us to use the event handler "onkeyup".
One example:
First Input field: 3 -> typed in
Second Input field: 97 -> will be shown automatically after typing 3
Please don't laugh, here is my code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc() {
var firstnum = document.getElementById("firstprop").value;
var secondnum = document.getElementById("secondprop").value;
var firstresult = 100 - parseInt(secondnum);
var secondresult = 100 - parseInt(firstnum);
if(firstnum >=0){
secondnum = secondresult;
}
if(secondnum >=0){
firstnum = firstresult;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc()" id="firstprop"/>
<input type="text" onkeyup="calc()" id="secondprop"/>
</body>
</html>
Thank you very much for your help. I appreciate it, really :)
Here you are
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc(value, index) {
if (index == 1) {
document.getElementById("secondprop").value = 100 - value;
} else if (index == 2) {
document.getElementById("firstprop").value = 100 - value;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc(this.value, 1)" id="firstprop" />
<input type="text" onkeyup="calc(this.value, 2)" id="secondprop" />
</body>
</html>
function calc(e) {
if (e.target.id === "firstprop") {
var secondElement = document.getElementById("secondprop");
var value1 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value1));
}
if (e.target.id === "secondprop") {
var secondElement = document.getElementById("firstprop");
var value2 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value2));
}
}
</script>
i want to know that when we type the name in input field type text. i want to get the input by user but while typing i want to capitalize the 1st letter that user enter. please help me
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form name="inputform">
Name: <input name="name" type="text" id="n" onKeyPress="check()">
</form>
<script>
function check()
{
var name=document.getElementById("n");
var uppercase=name.value.charAt(0);
}
</script>
</body>
</html>
As simple as it gets:
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}; // ^ First letter + The rest of the string.
Use it like this:
function check() {
var name = document.getElementById("n");
var uppercase = capitalizeFirstLetter(name.value);
name.value = uppercase;
}
Or, shorter:
<input name="name" type="text" id="n" onKeyUp="check(this)">
function check(element) {
element.value = capitalizeFirstLetter(element.value);
}
use this function in check method
like this
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
function check()
{
var name=document.getElementById("n");
var uppercase = capitalize(name)
}
You can use the Javascript function toUpperCase().
Here you have the code:
document.getElementById("n").addEventListener("keyup",checkinput);
function checkinput(){
var name=document.getElementById("n");
if(name.value.length==1){
var uppercase=name.value.charAt(0).toUpperCase();
name.value=uppercase;
}
}
I have a input field for user to input number. This number will be displayed in span tag as user is typing. And i would like to format this number in span tag with thousand separator.
Currently, it only show exactly what is typing without thousand separator:
JSFiddle
Here is my simplified code:
<!DOCTYPE html>
<html>
<head>
<script>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = x;
}
</script>
</head>
<body>
<form>
Price: <input type='text' id='frm_price'
onkeyup="charPreview()">
<span id="frm_price_preview"></span>
</form>
</body>
</html>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = decimalWithCommas(x);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function decimalWithCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
An answer without loops.
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = numberWithCommas(x);
}
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
See also accounting.js which handles this sort of thing quite nicely.
So all this time I thought I was doing it wrong. But can jQuery read decimals? My first textbox has to multiply the input with .10, the second is .05. But I only get 1 as final result. How can I fix it?
<!DOCTYPE html>
<head>
<title>Test</title>
<script src="../js/jquery-1.11.1.min.js"></script>
<head>
<body>
<input id="first" type="text" />
<script>
$('#first').on('change', function () {
$(this).val($(this).val() * .10);
compute();
});
</script>
<input id="second" type="text" />
<script>
$('#second').on('change', function () {
$(this).val($(this).val() * .05);
compute();
});
</script>
<script>
function compute() {
var first = ~~$('#first').val();
var second = ~~$('#second').val();
var result = $('#result');
var grade = first + second;
result.val(grade);
}
</script>
<input id="result" type="text" readonly />
</body>
</html>
I believe you want to change compute() to this:
function compute() {
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
var result = $('#result');
var grade = first + second;
result.val(grade);
}
I am trying to get the initials (upper case letters) of the name that the user enters inside the text field. I get and error that my function getInitials() is not defined. Why do I get this error? Also I want to check if the function exists with typeof.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Second task HS</title>
</head>
<body>
<form name="myForm" id="eForm" action="#">
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials();"/>
</form>
<div id="result">
</div>
<script type="javascript">
var nameInput = document.getElementById('name').value;//I need to stringify the input and use it!
var arr, nameArr, first, last;
nameArr = name.split(' ');
first = nameArr[0][0].toUpperCase();
last = nameArr[nameArr.length - 1][0].toUpperCase();
if(typeof getInitials == 'function'){
function getInitials(nameArr) {
return {first: first, last: last};
}
getInitials(nameInput);
}else{
alert('Check getInitials!');
}
</script>
</body>
</html>
From what I see, you are checking if the function exists... before creating it !
Try rather this JS code :
function getInitials( nameInput ) {
var nameArr = nameInput.split(' ');
return {
first: nameArr[0][0].toUpperCase(),
last: nameArr[nameArr.length - 1][0].toUpperCase()
};
}
function getInitialsFromInput() {
var nameInput = document.getElementById('name').value;
if(getInitials instanceof Function){ //strictly speaking, useless because it is obviously a function
alert(getInitials(nameInput));
}else{
alert('Check getInitials!');
}
}
getInitialsFromInput() ;
(and use "getInitialsFromInput()" for the onclick to gather the input's value)
You missed the text in <script type="javascript">, the statement should be like this <script type="text/javascript">
Here is the simple version of what you wanted, try it, this program expects first name Or first and last name only.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Second task HS</title>
<script type="text/javascript">
var arr, first, last;
function getInitials() {
var nameInput = document.getElementById('name').value; //I need to stringify
nameArr = nameInput.split(' ');
if(nameArr.length > 1){
first = nameArr[0].toUpperCase();
last = nameArr[1].toUpperCase();
}else{
first = nameInput.toUpperCase();
}
var result = {first: first, last: last};
alert(result.first);
alert(result.last);
}
</script>
</head>
<body>
<label for="name">Name</label>
<input type="text" id="name" name="fullname"/><br>
<input name="button" type="button" value="Pick" onclick="getInitials()"/>
<div id="result">
</div>
</body>
</html>
Your code makes no sense. getInitials Just is not assigned initially, so the inline click handler within the button will never work.
If you need the input value with first characters uppercased and initials, try something like:
document.querySelector('button[value=Pick]').onclick = getInitials;
function getInitials(e) {
var value = document.querySelector('#name')
.value.split(/\s+/)
.map( first2Upper );
if (value[0].length){
var ret = {first: value[0],
last: value[1],
initials: value[0][0] +(value[1] && value[1][0] || '')};
document.querySelector('#result').innerHTML =
value.join(' ') + ' (initials: '+ret.initials+')';
return ret;
} else {
alert('please enter a value');
}
}
function first2Upper(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
Here's a mockup in jsFiddle