Best method for submitting disabled form fields in jQuery?
Asked Answered
W

3

7

There seem to be several ways to submit (POST) disabled form fields in jQuery:

  • Have a hidden field that changes when the input changes, and submit that
  • Manually append the key/value pairs upon submission
  • Revert values on the server-side (only if values not expected to change)

I was wondering which (if any) is considered best practice for submitting disabled form fields. Obviously readOnly is the best option when it's available, but I have checkboxes that I need to submit even though they are disabled (due to business logic). I realize this is not an ideal situation, but rarely is that the case in web development.

Is there a best-practice for submitting disabled form elements?

Woodring answered 13/1, 2012 at 18:0 Comment(3)
The disabled form elements shouldn't be submitted. The correct way to do that, is creating hidden inputs on submit. Here's the HTML documentation: w3.org/TR/html4/interact/forms.html#successful-controlsZymo
@Dave So you're saying option 1 is the best choice? That's what I was leaning towards, too. Also, thanks for the documentation.Woodring
@GrailsGuy With regards to your first option, if you have a disabled form field, why would the input ever change?Lyn
E
8

The best option is to make the inputs readonly - create a click event for the check boxes that simply returns false, and change their background color.

There is no best practice, but that one requires the least fudging.

Epicardium answered 13/1, 2012 at 18:7 Comment(0)
N
5

A fourth solution would be to enable the check boxes before submitting the form:

$("form").submit(function() {
    $("input:checkbox", this).prop("disabled", false);
});

You can use a more sophisticated selector if you do not want to re-enable all the check boxes.

Narine answered 13/1, 2012 at 18:8 Comment(0)
Q
0

There is another way if require to post all or certain disbaled inputs:

  1. Step1: give a class name name (eg. mod).
  2. Step2: onSubmit, enabled all the those fields following the example below:

    $("input[class=mod]").removeAttr('disabled');

  3. Step3: Post data

  4. Step4: Disable those fields again (if required) following the example below:

    $("input[class=mod]").attr('disabled="disabled"');

Quadrivalent answered 20/6, 2014 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.