Home > Software design >  Resubmitting a date (HTML) without refreshing page once a submission is made
Resubmitting a date (HTML) without refreshing page once a submission is made

Time:02-22

I am creating an HTML page that takes a date from an input type="date" and returns the zodiac sign for that date. I have used a JS function to split the date into an array and use the indexes to isolate the month and day. The program runs as expected and displays the correct zodiac sign. But, if I submit the date and then change it, it keeps the original selection, unless I refresh the page.

Is there a way to change the input without refreshing the page? Or once submitted, is it static?

I select a date that displays the zodiac sign e.g. 'Taurus', then without refreshing the page, I select a date that represents 'Aries', but the display remains 'Taurus'. Do I need to refresh the page if I want to select and resubmit a different date or is there a way to achieve this without refreshing the page?

let userDate = document.querySelector('.selectedDate').value;
document.querySelector('.enterDate').addEventListener('click', findZodiac);

function findZodiac() {
  let sign = "";
  let selectedDate = new Date(userDate);
  let month = (selectedDate.getUTCMonth())   1;
  let day = (selectedDate.getUTCDate());
  let zodiacDisplay = document.querySelector('.starDisplay');

  if (month == 3 && day > 20 || month == 4 && day < 20) {
    sign = "Aries";
  } else if (month == 5 && day < 21 || month == 4 && day > 19) {
    sign = "Taurus";
  }

  zodiacDisplay.innerText = sign;
}

CodePudding user response:

The problem is that you are pre-caching the initial value of the form:

let userDate = document.querySelector('.selectedDate').value;

Then every time findZodiac() is called it is still referring to the stale copy of userDate. There's no reason you can't query and manage that value locally inside the findZodiac function.

  • Related