Jim Priest
Jim Priest

Reputation: 173

jQuery - can I validate a disabled field?

I've got a form where the user needs to click a link, select a user via a popup window which then populates a hidden field with an ID and a display field with the username.

The display field is set to disabled="disabled" to force the user to use the popup and not type a value in the field.

I need to ensure the user selects a name. I'm using jQuery and Jorn's validation plugin.

Doing a required: true on the disabled field doesn't seem to fire off if the value is blank.

Any ideas how to solve this?

Upvotes: 14

Views: 15225

Answers (4)

I used this code.

if($('#element').prop('disabled')){
   $('#element').prop('disabled', false);
   $('#element').valid();
   $('#element').prop('disabled', true);
}

Upvotes: 0

Gaetano
Gaetano

Reputation: 31

According to the previous suggestion the possible solution could be:

var _valid = $.fn.valid;
$.fn.valid = function (alsoDisabled) {
    var alsoDisabled = alsoDisabled || false;
    if (alsoDisabled) {
        this.find('[disabled]').prop('disabled', false);
    }
    var retVal = _valid.apply(this);
    if (alsoDisabled) {
        this.find('[disabled]').prop('disabled', true);
    }
    return retVal;
};


and so you could call the valid method with the optional arguments: $('#form').valid(true) to check also disabled field or $('#form').valid() for the normal behaviour

best regards Gaetano

Upvotes: 3

naikus
naikus

Reputation: 24472

Instead of making it disabled, have you tried making it readonly?

<input type="text" readonly="readonly" />

I remember from years ago that disabled fields are not submitted by forms, and hence probably are not validated

Here is the W3C HTML4 Spec on the topic.

Upvotes: 29

Val
Val

Reputation: 17522

why not enable it just befor validation and then disable it again... using the .attr('disabled','') to enable it and then .attr('disabled','disabled') to disable it again it will happen so quick you wont even notice it.

Upvotes: 1

Related Questions