I have a problem with datetime-local picker in HTML5. I want to clear the datetime with the clear button, but this is not possible because the "required" function inside the input will not allow. I will let a piece of code to see the differences. One is with required and one without required. Do you know how to keep the "required" and also clear the input from ex: "15/03/2022 00:00 AM" to mm/dd/yyyy --:-- --. Thank you.
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
<label for="meeting-time">Choose a time for your appointment:</label>
<input type="datetime-local" id="meeting-time"
name="meeting-time">
CodePudding user response:
The attribute required is responsible for whether the reset button is shown or not. If required is set, you must solve the reset programmatically. You do this for the type datetime-local
with yourDateElement.valueAsDate = null
.
const clearBtn = document.getElementById('clear-btn');
clearBtn.addEventListener('click', () => {
const d = document.getElementById('start_timestamp');
d.valueAsDate = null
})
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" value="" required>
<button id="clear-btn" onclick="clear()">clear</button>
<label for="meeting-time">Choose a time for your appointment:</label>
<input type="datetime-local" id="meeting-time"
name="meeting-time">
Works for Chrome too
const clearBtn = document.getElementById('clear-btn');
clearBtn.addEventListener('click', () => {
const d = document.querySelector('input[type=datetime-local]');
d.value = 0
})
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" value="" required>
<button id="clear-btn" onclick="clear()">clear</button>
<label for="meeting-time">Choose a time for your appointment:</label>
<input type="datetime-local" id="meeting-time"
name="meeting-time">
CodePudding user response:
I'm affraid it's not possible.
You should add your own clear button next to each input
:
function clearInput(id) {
document.getElementById(id).value = "";
}
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
<button type="button" title="clear" onclick="clearInput('start_timestamp')">x</button>
<label for="meeting-time">Choose a time for your appointment:</label>
<input type="datetime-local" id="meeting-time"
name="meeting-time">
<button type="button" title="clear" onclick="clearInput('meeting-time')">x</button>