I need help fixing my html and java script code
P粉201448898
2023-08-01 20:25:03
<p>I want to make a place where you can enter your next birthday and the page will turn into a window. Remind you that your birthday is in a few days. When I run the code, before I enter the birthday, the alert says NaN, which means is not a number. I want it to work after I type my birthday and after I click submit. This is the code I wrote:</p>
<p>`
</p>
<pre class="brush:php;toolbar:false;"><input type="submit" value="Submit">
</form>
<script>
let date_1 = new Date(document.getElementById("bday").value);
let date_2 = new Date();
let difference = date_1.getTime() - date_2.getTime();
let TotalDays = Math.ceil(difference / (1000 * 3600 * 24));
window.alert(TotalDays);
</script>
</body>`</pre>
<p><br /></p>
<!DOCTYPE html> <html> <head> <title>Birthday Countdown</title> </head> <body> <form onsubmit="calculateDaysLeft(event)"> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday" required> <input type="submit" value="Submit"> </form> <script> function calculateDaysLeft(event) { event.preventDefault(); // Prevent form submission to avoid page reload // Get the user's birthday from the input field let userBirthday = new Date(document.getElementById("bday").value); // Get the current date let currentDate = new Date(); // Calculate the difference in milliseconds let difference = userBirthday.getTime() - currentDate.getTime(); // Calculate the difference in days and show the alert let totalDays = Math.ceil(difference / (1000 * 3600 * 24)); window.alert(`There are ${totalDays} days left until your birthday!`); } </script> </body> </html>