I tried:
$(\'input\').keyup(function() {
$(this).attr(\'val\', \'\');
});
but it removes the entered text slightly after a letter is enter
If you want to prevent the user from adding anything, but provide them with the ability to erase characters:
<input value="CAN'T ADD TO THIS" maxlength="0" />
Setting the maxlength
attribute of an input to "0"
makes it so that the user is unable to add content, but still erase content as they wish.
<input value="THIS IS READONLY" onkeydown="return false" />
Setting the onkeydown
attribute to return false
makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.
A non-Javascript alternative that can be easily overlooked: can you use the readonly
attribute instead of the disabled
attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out")
e.g. <input readonly type="text" ...>
Markup
<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
TabIndex="1">
Script
function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}
For a css-only solution, try setting pointer-events: none
on the input.
$('input').keydown(function(e) {
e.preventDefault();
return false;
});