0

I have an MVC3 form with a single field on it - I don't want the form to actually be submitted, but be used with ajax to return JSON data for display on the screen.

I want to use a ViewModel/Form so that my validation with error messages is called and displayed relatively nicely, and I can also call remote validation as well.

However, when the user is entering data in the field, they can hit Enter and the form submits - which posts to the controller and returns a new, clear page :(

I have tried disabling the form submit - but it doesn't seem to work?

$(document).ready(function () {

    $('form').submit = function (e) {
        alert('submit');
         e.preventDefault();
        return false;
    };
.....

I've also tried moving the button out of the form, but (as expected) that doesn't make any difference.

@using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <div>
            <span class="editor-label">@Html.LabelFor(model => model.AccountNumber)</span>
            <span class="editor-field">@Html.TextBoxFor(model => model.AccountNumber, new { @id = "accountNumber", size = "15" })
                @Html.ValidationMessageFor(model => model.AccountNumber)</span>
        </div>
    }
    <div>
        <button type="button" id="generate" class="generate">
            Generate</button>
    </div>

How can I stop Enter submissing my form?

BlueChippy
  • 5,935
  • 16
  • 81
  • 131

2 Answers2

2

Try this

@Html.TextBoxFor(model => model.AccountNumber, new { @id = "accountNumber", size = "15",onkeydown="return (event.keyCode!=13);" })
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
1

You can use this (replace '=' on brackets):

$('form').submit(function(e) {
    alert('submit');
    e.preventDefault();
    return false;
});

This is worked for me

Boris Parfenenkov
  • 3,219
  • 1
  • 25
  • 30