how to make a counter that is 4 digit spaces long? [duplicate] - javascript

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Unique ID that gets a date in specific format?
(2 answers)
Closed 8 years ago.
I have a generate id button, when I click on the button it generates the date '2013-06-13' in a textbox. I want to add a 4 digit counter to the end of it so it will look like this '2013-06-13-xxxx' (0001, 0002, etc). When I click on the the generate button I want it to show '2013-06-13-0001' then I will push a submit button and the form will reset. When I push the generate id button again I want it to show '2013-06-13-0002' what code may I use to do this?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
This is the output code
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}

You can use this:
var str = '000' + Counter();
var result = str.substring(str.length - 4);
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + result);

I think here is what you looking for How to output integers with leading zeros in JavaScript
like this function below
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length-size);
}
and actually you just need s = "000" + num;

Related

join() Not Removing Commas from Array

I am trying to complete a Kata whereby I create a phone number from a given array input.
Input: [1,2,3,4,5,6,7,8,9,0]
Output: (123) 456-7890
The issue I have is that once I have built my string, when I call join(''), the commas are not being removed. My results is still: (1,2,3) 4,5,6-7,8,9,0.
What is the issue with the code that is preventing this happening?
function createPhoneNumber(numbers){
var newNum = [];
newNum.push("(" + numbers.slice(0,3) + ")" + " " + numbers.slice(3,6) + "-" + numbers.slice(6,10));
return newNum.join('');
}
It sounds like the numbers parameter is an array:
function createPhoneNumber(numbers) {
var newNum = [];
newNum.push("(" + numbers.slice(0, 3) + ")" + " " + numbers.slice(3, 6) + "-" + numbers.slice(6, 10));
return newNum.join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
In which case .sliceing it will produce another array, from the specified indicies, and using + with an array will result in concatenation. When the array gets implicitly turned into a string, its elements will be joined by a comma.
Join the sliced array while concatenating instead (and don't create a newNum array):
function createPhoneNumber(numbers) {
return "(" + numbers.slice(0, 3).join('') + ")" + " " + numbers.slice(3, 6).join('') + "-" + numbers.slice(6, 10).join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
A nicer option would be to join the numbers into a string first:
function createPhoneNumber(numbers) {
const numStr = numbers.join('');
return `(${numStr.slice(0, 3)}) ${numStr.slice(3, 6)} - ${numStr.slice(6)}`;
}
console.log(createPhoneNumber('1234567890'.split('')));
I would recomment that you use template literals introduced in es6:
function createPhoneNumber(numbers){
const phNo = `(${numbers.slice(0,3)}) ${numbers.slice(3,6)}-${numbers.slice(6,10)}`
return phNo
}
createPhoneNumber('1234567890') // output ==> (123) 456-7890

convert javascript string to regular expression [duplicate]

This question already has answers here:
Match #(\w+) and replace in javascript
(2 answers)
Closed 6 years ago.
I have the following
function arrayInArray(chBox, values) {
try {
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "/\b" + chBox[x] + ",?\b/";
var patt = new RegExp(eval(stringConcat));
console.log("value to check: " + chBox[y] + " " + values + " index " + patt.test(values));
but I can't get it to work. if I change it to this
var patt = new RegExp(/\b17,?\b/)
and then run
patt.test(values)
it works fine.
I'm passing in
var checkbox = ["17", "23"];
Can anyone tell me where I am going wrong
thanks
the code that works
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "\\b" + chBox[y] + ",?\\b";
var patt = new RegExp(stringConcat);
if (patt.test(values) == false) return false;
}
There's no need for eval as its already a string. Just pass that to the RegExp constructor. You should also drop the leading and trailing / as that will be interpreted as part of the expression.

Setting value to datetime-local HTML input

I have an HTML input object of type="datetime-local" to which I would like to set a custom value which is now() + 3 hours everytime its value is changed.
Basing on the fact that alert(object.value) returns a string of type YYYY-MM-DDTHH:MM, I've thought I would need (apart for calculating the date) also to format the string properly. So I have:
Added the onchange attribute to the HTML
<input .... onchange="datesReactions()"/>
Extended the JS Date prototype to add the hours
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Created the datesReactions() function as follows
function datesReaction(){
var adesso = new Date;
document.getElementById('ExecutionDate').value = parseDateToInput(adesso.addHours(3));
}
where the parsing to string is performed by the following simple function:
function parseDateToInput(jsDate){
var jsDay = jsDate.getDate();
if (jsDay < 10){jsDay = '0' + jsDay;}
var jsMonth = jsDate.getMonth();
if (jsMonth < 10){jsMonth = '0' + jsMonth;}
var jsYear = jsDate.getFullYear();
if (jsYear < 10){jsYear = '0' + jsYear;}
var jsHour = jsDate.getHours();
if (jsHour < 10){jsHour = '0' + jsHour;}
var jsMinute = jsDate.getMinutes();
if (jsMinute < 10){jsMinute = '0' + jsMinute;}
return jsYear + '-' + jsMonth + '-' + jsDay + 'T' + jsHour + ':' + jsMinute;
}
However, although the single pieces of code work themselves, the above does nothing when I change the value of my input.
Could anyone please help me understanding what I do wrong? I have prepared the following fiddle in order to help you helping a beginner debugging :) Thanks in advance.

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

telephone number format with jquery&regex done [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
telephone number format with jquery&regex
i need to verify and convert any input val into telephone number format, i.e
input er+f375g25123435s67 i need to convert into +375 25 1234567
a most suitable code is:
$('input').live({
keyup: function(){
ipt = $(this).val().replace(/[^\d]*/g, "");
// remove non-digits
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14);
$(this).val(ipt);
}
});
but i can't enter numbers after +375
1) how to enable numbers after +375
2) how to convert ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14) into regular expression?
HERE'S AN ANSWER: http://jsfiddle.net/5UvJr/
You may possibly want to look at this: http://digitalbush.com/projects/masked-input-plugin/
The substring indexes are wrong, try this:
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(3, 5) + " " + ipt.substring(5, 12);
here is an answer: http://jsfiddle.net/5UvJr/
$('input').live({
keyup: function(){
var phone = $(this).val().replace(/\D/g, '');
phone = phone.substring(0,12);
var myRegexp = /(\d{3})(\d{2})(\d*)/g
var mphone = myRegexp.exec(phone);
$(this).val('+' + mphone [1] + ' ' + mphone [2] + ' ' + mphone [3]);
}
});

Categories

Resources