Using JQuery, how can I make a field editable, but user can't type?
I have a field that has a date control popup when the user clicks in it. The problem is, that 开发者_运维技巧the user can also enter invalid dates.
Is there a way using Javascript to leave the field editable, but prevent the user from typing any numbers?
I think you want a readonly field:
<input type="text" readonly="readonly" /
>
It can still be modified with javascript and you can still intercept click events, but the user cannot type in it or copy/paste in it or drag/drop to it.
Demo here: http://jsfiddle.net/jfriend00/9SsZq/
Options that try to intercept keystrokes may not prevent everything (like drag/drop). It makes more sense to use the built-in readonly capabilities.
You could bind keydown handler to that text field and return false number was pressed:
$('#field_id').keydown(function(event){
if(event.keyCode > 47 && event.keyCode < 59)
return false;
return true;
});
if you want to also prevent ctrl-v and context menu(to be able to paste from it) use
$('#field_id').keydown(function(event){
var k = event.keyCode;
if((k > 47 && k < 59) || (k == '86' && event.ctrlKey))
return false;
return true;
}).bind('contextmenu',function(e){
return false;
});
for linux you should also consider preventing middle click paste :)
Update ignore my answer and use the widely supported readonly
attribute @jfriend00 mentions.
Original:
You could try to prevent the default action for keydown
, but users will still be able to paste (or find other "clever" ways to get unwanted data into it).
$('input[type="text"]').keydown(function(e) {
e.preventDefault();
}
.change(function() {
// Put default value back in
// NOTE: this only fires when focus is lost
});
A better option would probably be to use the disabled
property and use CSS to make it look right.
<input type="text" class="looks-enabled" disabled="disabled" />
精彩评论