I tried:
$(\'input\').keyup(function() {
$(this).attr(\'val\', \'\');
});
but it removes the entered text slightly after a letter is enter
if you don't want the field to look "disabled" or smth, just use this:
onkeydown="return false;"
it's basically the same that greengit and Derek said but a little shorter
just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.
<asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
</asp:TextBox>
$('input').keypress(function(e) {
e.preventDefault();
});
One other method that could be used depending on the need $('input').onfocus(function(){this.blur()});
I think this is how you would write it. I am not proficient in jquery.
I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:
//.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !
to prevent actions on a HTML input DOM element add readonly to class:
var d = document.getElementById("div1");
d.className += " readonly";
OR in D3:
.classed("readonly", function(){
if(condition){return true}else{return false}
})
AND add to CSS or less:
.readonly {
pointer-events: none;
}
the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).
to remove the element from class:
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\breadonly\b/,'');
or use Jquery:
$( "div" ).removeClass( "readonly" )
or toggle the class:
$( "div" ).toggleClass( "readonly", addOrRemove );
Just to be complete, good luck =^)
One option is to bind a handler to the input
event.
The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).
Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.
This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input
event is received.
const inputEl = document.querySelector('input');
inputEl.addEventListener('input', (event) => {
event.target.value = '';
});
<input type="text" />
Tested in Safari 10, Firefox 49, Chrome 54, IE 11.