0

I have an HTML form, and I would like it so that when the user clicks the submit button, the button and all input elements (textboxes mainly) in the form are disabled, to prevent them from changing any data, or clicking the button a second time. I'm using jQuery.validate on the form without the unobtrusive plug-in.

The markup for the form looks like this (irrelevant markup removed for clarity)...

<form method="post" asp-controller="Home" asp-action="Jim">
  <div class="form-group row">
    <label for="Name">Your name</label>
    <input type="text" id="UserName" name="UserName">
  </div>

  <div class="form-group row">
    <label for="Email">Email</label>
    <input type="text" id="Email" name="Email">
  </div>

  <div class="form-group row">
    <div>
      <button type="submit">Submit</button>
    </div>
  </div>
</form>

I have the following JavaScript that uses jQuery.validate...

$("form").validate({
  rules: {
    UserName: {
      required: true,
      minlength: 3
    },
    Email: {
      required: true
    },
    Message: {
      required: true
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});

That's all the JavaScript on the page.

This works fine. However, if I add one line into the submitHandler function...

  submitHandler: function(form) {
    $("form input").prop('disabled', true);
    form.submit();
  }

...then when the form is submitted, Request.Form is empty, so none of my data is sent to the server.

It seems to be related to jQuery.validate, as if I completely replace the JavaScript with this...

$(function() {
  $("form").submit(function(form) {
    $("form input").prop('disabled', true);
  });
});

...then the controls are disabled and my data comes through fine. This seem to imply I'm doing something wrong with jQuery.validate.

Anyone able to explain why my data doesn't come through when I disable the controls when using jQuery.validate?

Avrohom Yisroel
  • 8,555
  • 8
  • 50
  • 106

1 Answers1

1

The reason is that disabled inputs are not submitted with the form.Refer to here and here.

You should use the readonly attribute rather than disabled. Read-only fields cannot be edited by the user, but are still submitted with the form.

submitHandler: function (form) {
    $("form input").prop('readonly', true);
    form.submit();
}
Ryan
  • 19,118
  • 10
  • 37
  • 53
  • That's great, exactly what I wanted. makes more sense to use `readonly` I guess, although I'm still puzzled why the data was posted when I didn't use `jQuery.validate` – Avrohom Yisroel May 09 '19 at 12:18