Generate automatic number by selecting an option - javascript

The code that generates my number:
<input type="radio" class="alege" name="uni_code_type" id="alegeT" value="T" onclick="getUniCode()">
<label for="alegeT" class="control-label">T</label>
<input type="radio" class="alege" name="uni_code_type" id="alegeP" value="P" onclick="getUniCode()">
<label for="alegeP" class="control-label">P</label>
<input id="uni_code" name="uni_code" type="text" class="form-control">
and here is the corresponding JS:
var seq = 0;
// var d = new Date();
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = day + "/" + month + "/" + year;
function getUniCode() {
// Increment the value
seq += 1
// The string value that will be displayed
var value = document.querySelector('input[type="radio"].alege:checked').value;
// If sequence is less than 10, prefix with 000
if (seq < 10) {
value += '00' + seq + "-" + newdate;
}
// If sequence is less than 100, prefix with 00
else if (seq < 100) {
value += '0' + seq + "-" + newdate;
}
// If sequence is less than 1000, prefix with 0
else if (seq < 1000) {
value += '' + seq + "-" + newdate;;
}
// Otherwise, just use the value directly
else {
value += seq;
}
// Display the formatted value (ie prefixed with 0's)
document.getElementById("uni_code").value = value;
}
For now, if I select T, it generates a code like T001-6 / 4/2020 and if I select P and then I select T, this appears: P002-6 / 4/2020. I would like it after I press T and then press P to appear also at P all from 1 not from the number generated when I press T! Thank you!

I solve it thanks hehe :D ` var seq = 0;
// var d = new Date();
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = day + "/" + month + "/" + year;
function getUniCode() {
// Increment the value
seq += 1
// The string value that will be displayed
var value = document.querySelector('input[type="radio"].alege:checked').value;
// If sequence is less than 10, prefix with 000
if (seq < 10) {
value += '00' + seq + "-" + newdate;
}
// If sequence is less than 100, prefix with 00
else if (seq < 100) {
value += '0' + seq + "-" + newdate;
}
// If sequence is less than 1000, prefix with 0
else if (seq < 1000) {
value += '' + seq + "-" + newdate;;
}
// Otherwise, just use the value directly
else {
value += seq;
}
// Display the formatted value (ie prefixed with 0's)
document.getElementById("uni_code").value = value;
}
//
var seqe = 0;
// var d = new Date();
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = day + "/" + month + "/" + year;
function getUniCodee() {
// Increment the value
seqe += 1
// The string value that will be displayed
var value = document.querySelector('input[type="radio"].alege:checked').value;
// If sequence is less than 10, prefix with 000
if (seqe < 10) {
value += '00' + seqe + "-" + newdate;
}
// If sequence is less than 100, prefix with 00
else if (seqe < 100) {
value += '0' + seqe + "-" + newdate;
}
// If sequence is less than 1000, prefix with 0
else if (seqe < 1000) {
value += '' + seqe + "-" + newdate;;
}
// Otherwise, just use the value directly
else {
value += seqe;
}
// Display the formatted value (ie prefixed with 0's)
document.getElementById("uni_code").value = value;
}`
i did this and now it works as i want :D

Related

Javascript convert date to roman date

I have the following code that converts a date input into a roman date:
function romanize (num) {
if (!+num)
return false;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
}
$(document).on("change",'#date', function() {
var date = new Date($('#date').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
var strRomanDate = romanize(month) + " " + romanize(day) + " " + romanize(year);
$('#romandate .date').html(strRomanDate);
});
Now, this is working fine for some dates, for ex:
10/04/2018 --> X IV MMXVIII
But when I want to select a day after 12, so 13, 14,... It returns false false false.
Anyone have an idea what I should change in my code to make it work for every date?

Javascript increment and decrement YYYY-MM-DD by 1 day

I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>

Javascript - array override

I am writing a function to 'calculate' the dates of a working week based on the current date.
Console.log of the array's item is correct in the cycle, but when I print the content of the array at the end of the cycle, all the items have the same value.
I can't figure out what's wrong in my logic.
Any hing is much appreciated.
function calculateWorkingDays(){
var weekDates = ["0","1","2","3","4","5","6"];
var currentDate = new Date();
var weekDay = currentDate.getDay();
console.log("Initial weekDay: " + weekDay);
for (var i=0; i<7; i++){
console.log(i);
//check for Sunday (0)
if (weekDay==0){
weekDates[currentDate.getDay()] = currentDate;
//console.log("if i=0: day" + currentDate.getDay());
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
//set to Monday (1)
weekDay = 1;
currentDate.setDate(currentDate.getDate()-6);
} else {
if (weekDay<6) {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
weekDay = weekDay + 1;
} else {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
// set to Sunday (0)
weekDay = 0 ;
}
currentDate.setDate(currentDate.getDate()+1);
}
}
console.log(weekDates.toString());
}
The problem is that you fill weekDates array with the same content - DateTime object (stored in currentDate variable). And this incrementing line...
currentDate.setDate(currentDate.getDate()+1);
... doesn't assign a new object in currentDate - it augments the existing one instead.
The solution is: either clone or serialize this object (it depends on what you're going to do with it after).
As a sidenote, your approach can be simplified: instead of checking the dates inside the loop, just start the loop always from Monday. For example:
var currentDate = new Date();
var weekDay = currentDate.getDay();
if (weekDay === 0) {
weekDay = 7;
}
currentDate.setDate(currentDate.getDate() - (weekDay - 1));
var weekDays = [currentDate];
var currentTimestamp = +currentDate;
var msInDay = 1000 * 24 * 60 * 60;
for (var i = 1; i < 7; i++) {
weekDays.push(new Date(currentTimestamp + i * msInDay));
}
console.log(weekDays);
This code stores objects in an array; if that's not necessary, just serialize (with toString() or any other method fitting your needs) the stored DateTimes.

looping and print a list of time

var firstAm = '<li>12:00 AM</li>';
$('#time').append(firstAm);
for (i = 1; i < 12; i++) {
var am = '<li>' + i + ':00 AM</li>';
$('#time').append(am);
}
With above code I produced 1 hour interval, but I wish to produce something like
12:15 AM
12:30 AM
12:45 AM
which have 15 min different.
Fiddle : http://jsfiddle.net/ycjkqc0g/1/
You could do something like
var date = new Date();
date.setHours(0, 0, 0, 0);
var end = new Date(date);
end.setHours(end.getHours() + 12);
while (date < end) {
var am = '<li>' + convert24HourTo12Hour(date.getHours()) + ':' + date.getMinutes() + ' AM</li>';
$('#time').append(am);
date.setMinutes(date.getMinutes() + 15);
}
function convert24HourTo12Hour(h) {
return (h + 11) % 12 + 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
You can add one more loop inside the for loop as,
for (i = 1; i < 12; i++) {
for ( min = 0; min < 3; min++ ) {
var am = '<li>' + i + ':' + min * 15 + 'AM</li>';
$('#time').append(am);
}
}
In the inner loop you are basically printing the time in minutes as 0, 15, 30 and 45.
If you want to print it as '00' for hour, then you can format the number min*15 to a two digit value and use it.
var d = new Date();
d.setHours(0,0,0);
var html = '';
for (i=0;i<12*4*2;i++) {
var h = ('0'+d.getHours()).slice(-2);
var m = ('0'+d.getMinutes()).slice(-2);
var s = ('0'+d.getSeconds()).slice(-2);
var ampm = '';
if (h >= 12) {
ampm = 'pm';
} else {
ampm = 'am';
}
html += '<li>' + h + ':' + m + ':' + s + ' ' + ampm + '</li>';
d.setMinutes(d.getMinutes() + 15);
}
$(html).wrap('<ul></ul>');
$('#time').append(html);

Not getting date format using javascript

I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.

Categories