Suppose that i have 20 IMG Tags Which Remain Same But I Wanted to add a funcnalty where a user can select the city and date after selecting the city & date all image src changed according to user input.
Here is my img tags looks like:
<img src="https://www.example.com/2023/01/08/dl/01/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/02/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/03/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/04/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/05/image.jpg" alt="image"><br>
I created a form like this:
Here dl
is the city code.
<center><span>-: Select Your City :-</span><br>
<form action="" method="POST">
<select name="city">
<option value="">Select city...</option>
<option value="dl" selected>Delhi</option>
<option value="mb">Mumbai</option>
<option value="bl">Banglore</option>
<option value="hy">Hyderabad</option>
<option value="ch">Chennai</option>
<option value="ch">Kolkata</option>
</select>
<br><br>
<span>Select Date :-</span>
<br>
<input type="date" name="old" value="2023-01-08" min="2015-01-01" max="2023-01-08" required />
<br><br>
<input type="submit" value="Go" />
</form></center>
The default city should be Delhi & Date should be currnt date.
CodePudding user response:
To change imagesource like you want you'll have to use javascript. and make the date dynamic:
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}`;
// 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).padStart(2, '0');
image.src = `https://www.example.com/${date}/${city}/${imageNumber}/image.jpg`;
image.alt = `image nr:${index 1}of ${city} on ${date}`;
});
});
And the date input should just be changed to this:
<input type="date" name="old" min="2015-01-01" required />
Not sure what you want to achieve with this code but this does what you requested