Make Input Tag Toggle Between Edit And Readonly
Solution 1:
You can use the setAttribute and removeAttribute attribute functions to toggle disabled state.
const test = document.querySelector('#wasa');
const date = document.querySelector('#date');
test.addEventListener('click', function() {
if (date.hasAttribute('readonly')) {
date.removeAttribute('readonly')
} else {
date.setAttribute('readonly', 'readonly');
}
})
#wasa {
padding: 1em;
}
<divid='wasa'><inputid="date"type="date"value="2018-07-22"></div>
Solution 2:
If you are interested in a jQuery answer this would be how I would do it. It is a little more clean than a pure javascript answer and achieves the same thing.
// remove readonly when clicking on the input
$("body").on("click", "#wasa input", function(){
$(this).prop("readonly", "");
// EDIT: this was the prevoius answer//$(this).prop("readonly", !$(this).prop("readonly"));// unlock by clicking on the input
});
/* NEW */// lock input when click/tab away
$("body").on("focusout", "#wasa input", function(){
$(this).prop("readonly", "readonly");
});
#wasainput:read-only {
background: crimson;
color: white;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divid='wasa'><inputid="date"type="date"value="2018-07-22"readonly></div>
Solution 3:
You can use the change event to restore the readonly
status of the field.
From my comment...
Take off the toggle — start as readonly by including the readonly
attribute on the field
<input type="date" value="2018-07-22"readonly>
Then, when the div is clicked, remove the readonly attribute using date.removeAttribute('readonly')
as Nidhin shows.
When a new date is picked a change event is fired; attach a change listener to the date field. In that listener (when the field is changed) then add the readonly attribute back.
Note that a change
isn't always fired the moment a value changes, it may not be fired until you leave the field (blur), so you may want to further adapt the code below, but it is fired when you change the value via the datepicker.
const dateDiv = document.getElementById('wasa');
const date = document.querySelector('input[type=date]', dateDiv);
dateDiv.addEventListener('click', function() {
date.removeAttribute('readonly');
});
date.addEventListener('change', function() {
date.setAttribute('readonly','');
});
#date {
background: transparent;
border: none;
}
#date[readonly] {
background-color: lightblue;
}
<divid='wasa'><inputid="date"type="date"value="2018-07-22"readonly></div>
Post a Comment for "Make Input Tag Toggle Between Edit And Readonly"