Thousands separator using Period on Javascript Function (ASP.net) - javascript

Sorry if duplicated, but I really confused with these javascript.
Please help me, if willing.
I have this javascript function that already worked, this function will add thousands separator with commas :
function addCommas(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
And I call this function in the textbox, like this :
Number Format <asp:TextBox ID="txtPrice" runat="server" onkeyup="this.value=addCommas(this.value);"></asp:TextBox>
The output, looked like this (the separator using commas):
60,000,234
BUT I want the output, looked like this (the separator using period) :
60.000.234
Give me a solution still using these Javascript function, please. Thanks

I notice what was wrong in my code in comment.
Try this, I used it long time ago.
function addCommas(x) {
var retVal=x.toString().replace(/[^\d]/g,'');
while(/(\d+)(\d{3})/.test(retVal)) {
retVal=retVal.replace(/(\d+)(\d{3})/,'$1'+'.'+'$2');
}
return retVal;
}
Number <input type="text" onkeypress="this.value=addCommas(this.value);" onkeyup="this.value=addCommas(this.value);" />
I hope so this will help You.

function addCommas(x) {
x = '' + x;
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
It's still your function, but the variable x is converted into a string first.

Related

Enter a three digit number and write a function that adds the numbers together - Homework Warning

I have this homework problem with functions. I can get the user's string input into an array of numbers, but I cant figure out how to then add them. I tried doing a for loop but this seems like Im going down the wrong path.
Question:
Allow a user to enter a three digit number.
Write a function that adds the numbers together.
Hint #1: You need to turn a string into an integer.
Hint #2: Strings can be treated as arrays too.
Here is my code:
document.getElementById('submitBtn3').addEventListener
("click", function ()) {
var digits = document.getElementById('digits').value;
var digitsArray = digits.split(',').map(function(i) {
return parseInt(i, 10);
})
console.log(digitsArray);
document.getElementById('q11').innerHTML = digitsArray;
})
Any help appreciated
function add(a, b) {
return a + b;
}
document.getElementById('submitBtn3').addEventListener("click", function() {
var digits = document.getElementById('digits').value;
var sum = digits.split("").map(function(n){return parseInt(n)}).reduce(add,0);
document.getElementById('q11').innerHTML = sum;
});
<input id="digits" type="number"/>
<button id="submitBtn3">go!</button>
<div id="q11"></div>
You have some issues,
a closed parenthesis without the following block for the function
("click", function ())
// ^
splitting with split(','), which works only for joint arrays, like 1,2,3, but not with a string, without commas. You need here an empty string split('').
Now you can add the single numbers in another loop, or extend the first loop with an addition.
document.getElementById('submitBtn3').addEventListener("click", function() {
var digits = document.getElementById('digits').value;
var digitsArray = digits.split('').map(function(i) {
return parseInt(i, 10);
});
console.log(digitsArray);
document.getElementById('q11').innerHTML = digitsArray;
});
<input id="digits">
<button id="submitBtn3">go!</button>
<div id="q11"></div>
Just a hint for completeness.
Strings have a length property. This helps to iterate through a string with a loop of choice. The access inside could be with String#charAt or with brackets and an index, like string[index].
This one might be more homework answer friendly than using a 1 line .map
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
num.split('').forEach( function (x) {
tot = tot + parseInt(x,10);
});
document.getElementById('output').innerHTML = tot;
}
<input id="digits" />
<button onClick="myFunc()">Submit</button>
<div id="output"></div>

Coding html to display numbers so they are thousand separated

I've been trying all day long and nothing seemed to work.
What I'd like my website to do, is that I enter a value in a table cell in my code, and the displayed result would be the same value, but thousand separated. These values are strictly numbers, though on the page not every content is numbers exclusively.
I've tried dozens of different javascript codes to no avail and I'm starting to give up hope. I looked through my code and nothing seems to contradict each other, so what could be the problem? Is this really such a hard task to pull out?
Thank you very much for any input from you and the time to take to work on this problem with me! I'm eager to provide any info you'd possibly need to understand the situation better!
use toLocaleString
let numb=5934859384;
numb.toLocaleString('pl-PL')
or toFixed
let numb=82384.23456;
console.log(numb.toFixed(2));
or create function like:
function addDots(numb,position){
let str=numb.toString().trim();
let arr=str.split('');
let result='';
let index=0;
for(let i=arr.length-1;i>=0;i--){
index++;
let nr=arr[i];
result=nr+result;
if(index == position){
result='.'+result;
index=0;
}
}
let firstIsDot=result.substr(0,1);
if(firstIsDot=='.'){
result=result.substr(1);
}
return result;
}
let numb=3484762347;
console.log(addDots(numb,4)); // 34.8476.2347
if you want to replace numbers in table:
function replaceTableNumbers(){
let tds=$('td');
for(let i=0;i<tds.length;i++){
let td=tds[i];
let txt=$(td).text().trim();
if(txt.match(/^[0-9]+$/)!=null){
let parsed=addDots(txt,3);
$(td).text(parsed);
}
}
}
$(document).ready(function(){
replaceTableNumbers();
})
Does this solution work?
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Taken from: How to print a number with commas as thousands separators in JavaScript
You mean like this answer?
$('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, ",");
});
});

is it possible to check the XMLHttpRequestObject.responseText value using if condition

Is it possible to check the XMLHttpRequestObject.responseText value using if condition instead of just displaying it?
I have tried like this.
var a=XMLHttpRequestObject.responseText;
if(a=="false")
{
document.getElementById("show_mark").innerHTML =a;
}
I know its wrong,but i need to do like this.Is there any other alternative way for doing this?Help me i am completely a newbie to AJAX.
It is possible that the response text has added white spaces. To remove white spaces at the start and end of a string use string.trim().
In your case a=a.trim()
If trim is not available in your browser's JavaScript interpreter add in
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
Source
Finally i found the mistake.Its not the white spaces around the value.Actually its all the html tags like <html><body>false</body> etc., I removed these characters with the help of this code. I got the answer.
var a=XMLHttpRequestObject.responseText;
a = a.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var b = (a.replace(/<\/?[^>]+(>|$)/g, "")).trim();
if(b=="false")
{
document.getElementById("show_mark").innerHTML =b;
}
Thanks for the support.

Javascript - Detecting the first character and alerting the user

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

How to achieve String Manipulation in JavaScript

The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?
This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.
It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.
There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:
function incrementContract(name) {
var match = /^(.*)-R([0-9]+)$/.exec(name);
if (match) {
// Increment previous revision number
name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
}
else {
// No previous revision number
name += "-R1";
}
return name;
}
Live copy
You can use a regular expression for this:
s = s.replace(/(-R\d+)?$/, function(m) {
return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});
The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).
The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.
how you get renewal number? Calculating from date, or getting from database?
var renewal = 1,
name = 'myContract',
newname = name+'R'+renewal;
or maybe like
$(function(){
function renew(contract){
var num_re = /\d+/,
num = contract.match(num_re);
if (num==null) {
return contract+'-R1';
} else {
return contract.replace(num_re,++num[0]);
}
}
var str = 'myContract';
new_contract = renew(str); // myContract-1
new_contract = renew(new_contract); // myContract-2
new_contract = renew(new_contract); // myContract-3
});
Here jQuery can't help you. It's pure JavaScript working with strings
P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder

Categories

Resources