mercredi 7 février 2018

Date input and checkbox influencing each other bug

The code add/delete current date into the input if you click the checkbox.
If you enter or delete a date in the input it check/uncheck the checkbox.
The checkbox always works correctly, the input work as long as i have not pressed the checkbox, don't know why...

checkbox = document.getElementById('checkbox');
dateInput = document.getElementById('dateInput');

//Istance of setDate function 
checkbox.onchange = function() {
  setDate(checkbox, dateInput);
};

//Function to set date in input if checkbox is clicked
function setDate(checkbox, dateInput) {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();

  if(dd<10) {
      dd = '0'+dd;
  }

  if(mm<10) {
      mm = '0'+mm;
  }

  today = yyyy + '-' + mm + '-' + dd;
  if (checkbox.checked) {
    dateInput.value = today;
  } else {
    dateInput.value = '';
  }
};

//Add 'checked' property when input is not empty
dateInput.oninput = function() {
  if(dateInput.value != '') {
    checkbox.setAttribute('checked', 'checked');
  } else {
    checkbox.removeAttribute('checked');
  }

};
<input type="checkbox" id="checkbox">
<input type="date" id="dateInput">



Aucun commentaire:

Enregistrer un commentaire