How To Change Date Format Received From Input Field Using Javascript? - javascript

I Have a form where I received input from users using the form. Based on user input I changed the image src.
<center><span>-: Select Your City :-</span><br>
<form action="" method="POST">
<select name="city">
<option value="">Select city...</option>
<option value="de" selected>Delhi</option>
<option value="mu">Mumbai</option>
<option value="lc">Lucknow</option>
</select>
<br><br>
<span>-: Select Date :-</span>
<br>
<input type="date" name="old" value="2023-01-13" min="2021-01-01" max="2023-01-13" required />
<br><br>
<input type="submit" value="Go" />
</form>
</center>
<img src="https://image.example.com/images/13012023/13012023-de-1.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-2.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-3.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-4.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-5.jpg"><br>
<script>
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
// Get the form elements
const form = document.querySelector('form');
const citySelect = form.querySelector('select[name="city"]');
const dateInput = document.querySelector('input[type="date"]');
dateInput.value = `${year}-${month}-${day}`;
dateInput.max = `${year}-${month}-${day}`;
// Get the selected city and date values
const city = citySelect.value;
const date = dateInput.value;
// Get all the img elements
const images = document.querySelectorAll('img');
// Add an event listener to the form that will run a function
// when the form is submitted
form.addEventListener('submit', (event) => {
// Prevent the form from submitting and refreshing the page
event.preventDefault();
// Get the selected city and date values
const city = citySelect.value;
const date = dateInput.value;
// Get all the img elements
const images = document.querySelectorAll('img');
// Update the src attribute of each img element
images.forEach((image, index) => {
const imageNumber = String(index + 1);
image.src =
`https://image.example.com/images/${date.replace(/-/g, '')}/${date.replace(/-/g, '')}-${city}-${imageNumber}.jpg`;
});
});
</script>
Now I wanted to update the image tag src based on user input. But the problem is my code set the date in YYYYMMDD format but I want the date in DDMMYYY format to set the date in the image src.

Just add an id to the input to get its value
Then, splitting value with "-" will be ['2023', '01', '13']
Now, you can reverse the result to be ['13', '01', '2023'] and join them adding '-'
const newDate = date.split('-').reverse().join("-");
console.log(newDate);
<center><span>-: Select Your City :-</span><br>
<form action="" method="POST">
<select name="city">
<option value="">Select city...</option>
<option value="de" selected>Delhi</option>
<option value="mu">Mumbai</option>
<option value="lc">Lucknow</option>
</select>
<br><br>
<span>-: Select Date :-</span>
<br>
<input id = "date" type="date" name="old" value="2023-01-13" min="2021-01-01" max="2023-01-13" required
/>
<br><br>
<input type="submit" value="Go" />
</form>
</center>
<img src="https://image.example.com/images/13012023/13012023-de-1.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-2.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-3.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-4.jpg"><br>
<img src="https://image.example.com/images/13012023/13012023-de-5.jpg"><br>
<script>
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
// Get the form elements
const form = document.querySelector('form');
const citySelect = form.querySelector('select[name="city"]');
const dateInput = document.querySelector('input[type="date"]');
dateInput.value = `${year}-${month}-${day}`;
dateInput.max = `${year}-${month}-${day}`;
// Get the selected city and date values
const city = citySelect.value;
const date = dateInput.value;
// Get all the img elements
const images = document.querySelectorAll('img');
// Add an event listener to the form that will run a function
// when the form is submitted
form.addEventListener('submit', (event) => {
// Prevent the form from submitting and refreshing the page
event.preventDefault();
// Get the selected city and date values
const city = citySelect.value;
const date = dateInput.value;
// Get all the img elements
const images = document.querySelectorAll('img');
// Update the src attribute of each img element
images.forEach((image, index) => {
const imageNumber = String(index + 1);
image.src =
`https://image.example.com/images/${date.replace(/-/g, '')}/${date.replace(/-/g, '')}-${city}-${imageNumber}.jpg`;
});
});
</script>

Try this:
const date = dateInput.value;
const [year, month, day] = date.split('-');
const result = [day, month, year].join('/');
console.log(result);

You can use the toLocaleDateString according to your requirements, for example
<script>
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
var localDate = today.toLocaleDateString("en-uk");
console.log(today.toLocaleDateString("en-uk")); // 13/01/2023
localDate = localDate.split("/").join("");
console.log(localDate) //13012023
</script>

Related

how to Create a date input that only accepts a date that comes after today

I want to Create a date input that only accepts a date that comes after today, and if the user selected a date that comes before today you have to display an error message that describes that they can't do that.
what should i add to my code :
var myForm = document.getElementById('my_form');
myForm.addEventListener('submit', function(e){
var errors = "";
var ageInput = document.getElementById('age_input');
var nameInput = document.getElementById('name_input');
if (!ageInput.value || isNaN(ageInput.value))
{
ageInput.style.borderColor = 'red';
errors += 'age is invalid</br>';
} else {
ageInput.style.borderColor = 'inherit';
}
if(!nameInput.value) {
nameInput.style.borderColor = 'red';
errors += 'name is invalid\n';
} else {
nameInput.style.borderColor = 'inherit';
}
if (errors){
document.getElementById('errors').innerHTML = errors;
// to prevent the page from reloading
e.preventDefault();
}
});
<form id="my_form" action="submit.php">
<label>Age: </label>
<input type="text" id="age_input" />
<label>Name: </label>
<input type="text" id="name_input" />
<label>date: </label>
<input type="date" id="date_input" />
<button type="submit">submit</button>
<p id='errors'></p>
</form>
const datePicker = document.getElementById('date_input');
const selectedDate = new Date(datePicker.value);
const today = new Date();
today.setUTCHours(0,0,0,0);
if (isNaN(selectedDate) || selectedDate < today) {
errors += 'you can pick dates from the past</br>';
}

How to set php data to javascript date and change color of the input text

I'm trying to change the color of the input text whenever the$visa_expired is the same date as today. But right now, I get an error saying Invalid Date
Here is my code:
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "red";
window.alert(today);
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
Here is my HTML:
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
This is similar to what I have done in the past
var inputElement = document.getElementById("expiry");
var inputDate = inputElement.value;
var expired = new Date();
var today = new Date();
expired.setUTCFullYear(inputDate.split("/")[2], inputDate.split("/")[0] - 1, inputDate.split("/")[1]);
if(today === expired) {
inputElement.style.backgroundColor = "red";
window.alert(today);
} else {
inputElement.style.backgroundColor = "yellow";
}
Also it looks like you need to change
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
To
<input type="text" class="form-control" size="5" value="<?php echo $visa_expiry; ?>" id="expiry">
Just note that since you are using a input form box, its always possible that someone would enter something like 10-12-2016 instead of the 10/12/2016 format you may be expecting. Which would cause the above code to fail. You might want to consider finding a datepicker, or at the least change the
<input type="text">
to
<input type="date">
Then create some code to format the date to what you want.
References
How to change css property using javascript
Converting string to date in js
If 10/13/2016 is the value of $visa_expiry it should not give error.
check this link and run the fiddle it alert date.
http://phpfiddle.org/main/code/hpia-ub40
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (today >= expired) {
inputVal.style.backgroundColor = "red";
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
You are trying to display an Date Object in alert, which expects a string input. You should use getDate() instead.
try this:
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
today = day + '/' + month + '/' + year

How do I display a javascript value in dropdown field?

I got a trivial ask but I can't seem to work it out elegantly. I have an HTML form where I want to display the date (today & next 2 days, dd/mm) using javascript. The page is built on jQueryMobile.
Here's my HTML
<form>
<select name="departure" id="departure">
<option ><script>document.write(today);</script></option>
<option ><script>document.write(tomorrow);</script></option>
<option ><script>document.write(dayaftertomorrow);</script></option>
</select>
</form>
Here's my Javascript
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+'/'+mm;
//----------
var tomorrow = new Date(new Date().getTime() + 86400000);
var day = tomorrow.getDate()
var month = tomorrow.getMonth() + 1
if(day<10) {
day='0'+day
}
if(month<10) {
month='0'+month
}
tomorrow = day+'/'+month
//----------
var aftertomorrow = new Date(new Date().getTime() + 172800000);
var afterday = aftertomorrow.getDate()
var aftermonth = aftertomorrow.getMonth() + 1
if(afterday<10) {
afterday='0'+afterday
}
if(aftermonth<10) {
aftermonth='0'+aftermonth
}
aftertomorrow = afterday+'/'+aftermonth
Here's the JSFiddle
How would you go about this ?
Thanks
Greg
Take a look at this: http://jsfiddle.net/S8HZV/1/
I added an id to the options and I added 3 more lines to the script.
Try using innerHTML instead of document.write.
HTML:
<form>
<select name="departure" id="departure">
<option id="today"></option>
<option id="tomorrow"></option>
<option id="dayaftertomorrow"></option>
</select>
</form>
JavaScript:
document.getElementById('today').innerHTML= today;
document.getElementById('tomorrow').innerHTML= tomorrow;
document.getElementById('dayaftertomorrow').innerHTML= aftertomorrow;
You can create the option elements and insert them into the select with javascript.
For example, this is how you would add today as an option to the departure select
var select = document.getElementById('departure');
var option = document.createElement('option');
option.innerHTML = today;
select.appendChild(option);
For another option, this sets the value, too.
http://jsfiddle.net/isherwood/S8HZV/5/
document.getElementById('departure').options[0].val = today;
document.getElementById('departure').options[0].text = today;
document.getElementById('departure').options[1].val = tomorrow;
document.getElementById('departure').options[1].text = tomorrow;
document.getElementById('departure').options[2].val = aftertomorrow;
document.getElementById('departure').options[2].text = aftertomorrow;

javaScript code working in a seperate file but not part of a bigger file

I am making a simple Goal-traking completely offline HTML5 app using localStorage.
The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system.
I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy.
Here is the code that's working fine as a seperate file:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
window.onload = function(){
// setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data);
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.body.appendChild(document.createTextNode(
"The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
</BODY>
</HTML>
and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
function save()
{
//Get data from the form
var goal = document.getElementById("goal").value; //Get 'goal' from form
var date2 = document.getElementById("date2").value; //Get 'duedate' from the form
var active = document.getElementById("active").value; //Get 'active' from form
//Calculating the number of days remaining
var date1 = new Date(); //Current Date and Time
var dd = date1.getDate(); //Current Date
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear(); //Current Year
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy; //Parsing the date to the required format
var diff = Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000); //Calculate no. of days remaining
if (localStorage.getItem('gcount') === null) {
localStorage.setItem('gcount', "1");
var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);
//document.getElementById("temp").innerHTML="first";
}
else{
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
var goal = "CN"
var data = { "goal": goal, "duedate": date2, "noofdays": diff, "active": active};
goalsObj.goals.push(data);
localStorage.setItem("goals", JSON.stringify(goalsObj));
}
}
function load(){
/* // setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data); */
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;
document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;
document.getElementById("active").innerHTML=goalsObj.goals[i].active;
// document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
<form name="input" onsubmit="save(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>
<label>Active: </label><br>
<input type="radio" name="active" id="active" value="Future">Future <br>
<input type="radio" name="active" id="active" value="Present">Present <br> <br>
<!-- Submit button to submit the form -->
<input type="submit" value="submit">
</form>
<form name="load" onsubmit="load(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<input type="submit" value="submit">
<p id="temp"></p>
<p id="temp1"></p>
<p id="temp2"></p>
<p id="temp3"></p>
<p id="temp4"></p>
<p id="temp5"></p>
<p id="temp6"></p>
<p id="temp7"></p>
<p id="temp8"></p>
<p id="duedate"></p>
<p id="noofdays"></p>
<p id="active"></p>
</BODY>
</HTML>
I am getting the error that object is not a function. I have tried all other similar questions on StackOverflow and nothing worked.
What's wrong? What should I do?
You are using the same id for multiple different elements.
Also, try using IndexedDB instead of localStorage.

How to generalize the functions in Javascript

I have fromDate and toDate text boxes and when I select icon beside text boxes Calender will be displayed and when I select a date that date will be displayed in corresponding text boxes.
My intention is to use single generalized function for both toDate and fromDates. How can I do that, I am using YUI Calender and here is my code:
<td>
<strong>From Date</strong>
</td>
<td>
<input type="text" name="fromDate" id="fromDate" value="" size=15>
<img id="calendarFromIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarFromContainer"></div>
</td>
<td>
<strong>To Date</strong>
</td>
<td>
<input type="text" name="toDate" id="toDate" value="" size=15>
<img id="calendarToIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarToContainer"></div>
</td>
and the script for this is:
var myFromCalendar = new YAHOO.widget.Calendar("calendarFromContainer", {
close: true,
navigator: true
});
myFromCalendar.render();
myFromCalendar.hide();
function handleSelect(type, args, obj) {
var dates = args[0];
var date = dates[0];
var year = date[0];
month = date[1];
month = (month < 10) ? "0" + month : month;
day = date[2];
day = (day < 10) ? "0" + day : day;
var txtDate1 = document.getElementById("fromDate");
txtDate1.value = year+ "/"+ month + "/" + day;
myFromCalendar.hide();
}
myFromCalendar.selectEvent.subscribe(handleSelect,myFromCalendar, true);
YAHOO.util.Event.addListener("calendarFromIcon", "click", function(e) {
var calContainer = YAHOO.util.Dom.get("calendarFromContainer");
var selectedDate = document.getElementById("fromDate");
if (selectedDate.value) {
var matches = selectedDate.value.match(/^\s*0?(\d+)\/0?(\d+)\/(\d+)\s*$/);
var year = parseInt(matches[3]);
var month = parseInt(matches[1]);
var pageDate = month+"/"+year;
myFromCalendar.cfg.setProperty("pagedate", pageDate, false);
myFromCalendar.cfg.setProperty("selected", selectedDate.value, false);
myFromCalendar.render();
}
myFromCalendar.show();
});
You can use jquery to apply a single function to multiple HTML elements. Jqueries select function may help you.

Categories