3

I can't find any solution for this anywhere. I would like to allow user to see calendar when clicking on my input, but when user will try to change the value, it shouldn't change (or immediately change back for value, what was at the beggining).

Readonly attribute removes calendar, so I was trying to do it different ways like use onchange/onclick functions to restore my value after event, but the value was changing anyway.

So for now my input looks like this:

<input class='test' type='date' value='2020-06-04' onkeydown='return false' >

So at least user can't change value of my input using keyboard. Could you help me?

Kida
  • 734
  • 1
  • 9
  • 23

2 Answers2

3

You might try to set a time limit

<html>
<body>
<input type="date" value="2020-06-04">
<input type="date" value="2020-06-04" min="2020-06-04" max="2020-06-04">

</body>
</html>
  • Very nice, quick, easy and smart idea, thanks! – Kida Dec 04 '20 at 08:00
  • 1
    Here you still can change the day in second field in the snippet.Why is that? Also setting a min /max, we can still edit value out of range by typing. – MSQ May 10 '22 at 14:57
2

If I understood correctly, this is what you want.

HTML

<input class='test' type='date' value='2020-06-04' />

JavaScript

const date = "2020-06-04";
const input = document.querySelector('.test');

input.onkeydown = function(e) {
    return false;
}

input.onchange = function(e) {
    this.value = date;
}

Check out this JSFiddle

EDIT

function preventInputChange(input, staticValue) {
  input.onchange = function(e) {
    this.value = staticValue;
  }
}
kmp
  • 692
  • 6
  • 17
  • This one could work, but I mean a little bit more universal solution, which will work for many different inputs, so instead of using `const date` I would need for example to pass my input value to function somehow – Kida Dec 04 '20 at 08:52
  • Is this you're looking for? - Edited my answer – kmp Dec 04 '20 at 08:57
  • 1
    Instead of using `const date` you could store the date on the input itself using `$("#myinput").data("fixeddate", $("#myinput").value)` at startup then read from the data each time. Principle is the same as this answer - just a different storage location. – freedomn-m Dec 04 '20 at 09:19