Search code examples
asp.net-mvchtml.textboxfor

How to disable Submit behavior on readonly text box?


Have the following READONLY textbox:

 @Html.TextBoxFor(model => model.ClientNumber, new {@readonly = "readonly", @class ="message-label"})

and Save button:

 <button type="submit" id="btnSave" name="Command" value="Save">Save</button>

When user clicks on Client Number text box and hits Enter, then submit behavior is invoked and next page is displayed after data is saved to the database.

How to change this, so that hitting Enter while in this field does nothing, similar to how page behaves for a usual label?


Solution

  • You can do this with a little bit of javascript, handling keydown event and checking whether Enter was hit:

    $(document).ready(function() {
        $('input[name=ClientNumber]').keydown(function(e) {
            if (e.keyCode === 13) {
                e.preventDefault();
                return false;
            }
        });
    });