How to prevent user from typing in text field without disabling the field?

前端 未结 11 1668
不思量自难忘°
不思量自难忘° 2021-01-31 06:58

I tried:

$(\'input\').keyup(function() {

   $(this).attr(\'val\', \'\');

});

but it removes the entered text slightly after a letter is enter

相关标签:
11条回答
  • 2021-01-31 07:30

    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.


    But If you want it to be truly constant and unchangeable:

    <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.

    0 讨论(0)
  • 2021-01-31 07:38

    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" ...>

    0 讨论(0)
  • 2021-01-31 07:42

    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();}
    
    0 讨论(0)
  • 2021-01-31 07:43

    For a css-only solution, try setting pointer-events: none on the input.

    0 讨论(0)
  • 2021-01-31 07:44
    $('input').keydown(function(e) {
       e.preventDefault();
       return false;
    });
    
    0 讨论(0)
提交回复
热议问题