Disabling Select Drop Down List using jQuery without ‘disabled’

Say you have a drop down list defined as a select tag:

<select id="dropdown">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3" selected>Three</option>
</select>

You can very easily disable the drop down list with jQuery by adding a disabled property to the tag.

$('#dropdown').attr('disabled', 'disabled')

However, in doing that, the selected value of the drop down list is no longer posted back on a form submit. And some systems (such as SharePoint) may then persist the default value when saving changes, which in the example above is “1” instead of the selected “3”.

So instead of a straight forward disable, we’re forced to do some extra work to make sure the control remains disabled on the front end to the user, but still posts back the corrected selected value to the back end.

The JavaScript below achieves this:

function DisableDropdown($control) {
  $copy = $control.clone();
  $copy.removeAttr("id");
  $copy.removeAttr("name");
  $copy.attr("disabled", "disabled");

  $control.parent().prepend($copy);
  $control.hide();
}

DisableDropdown($('#dropdown'));

It’s basically creating a cloned copy and placing it before the original drop down control. The cloned copy is scrubbed of its id (to prevent duplicates) and name (to prevent its value being posted back), and set to disabled. The original drop down is then hidden, so its value is still being posted back, but is unseen to the front end users.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s