Reputation: 9840
When i click on a textfield
, i get a dropdown so the user could select a value from the list.
After the user selects the date from the dropdown, he/she could edit the date by even adding characters to it. So i want to find a way to prevent this. I thought of making the field un-editable. So i used readonly
but, this prevents the user from clicking and displaying the list. So can someone tell me how can i make the field uneditable.
<input id="datePiccc" type="text" class="dates" />
Upvotes: 0
Views: 10243
Reputation: 89750
You can use the below code. This will make the text input field clickable but when the user types in anything, nothing would happen.
document.getElementById('datePiccc').onkeydown = function(e){
e.preventDefault();
}
As pointed out by nnnnnn, onkeydown
is a better option than onkeypress
as it would stop the delete and backspace key functions.
You could add the below also to your code to nullify Cut and Paste events1. (Note: Not doing anything for Copy as that operation isn't going to change the value of the text field).
document.getElementById('datePiccc').oncut = function(e){
e.preventDefault();
}
document.getElementById('datePiccc').onpaste = function(e){
e.preventDefault();
}
1 I think these should work in all browsers. Currently tested in Chrome 31, Opera 15, IE10 and FireFox 24. (Note: In IE10, there is an x
mark which appears on the right side of the input field which when clicked clears the entire field value. Could not find a way around this.)
Upvotes: 5
Reputation: 1755
Disable the input in JQuery as
$("#datePiccc").attr("disabled", true);
And in pure JS
document.getElementById('datePiccc').disabled = true;
May be this can help!
Upvotes: 4
Reputation: 2753
I'm assuming the text field is being set in javascript. If so, you can use the following line to disable
the field:
document.getElementById('datePiccc').disabled=true;
The input will remain as it is and the value from the selection field can also be set.
Upvotes: 4