1. Home
  2. Snippets
  3. Disable a form field to prevent user input

Disable a form field to prevent user input

Heads up!

This article contains PHP and javascript code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

For extra guidance, please see WPBeginner's tutorial on adding custom code.

Dismiss

A disabled, or read-only, field can be useful if you’d like your users to see the field value but need to prevent that value from being changed.

This is also helpful when you’d like this value to be included in the {all_fields} Smart Tag for a notification email or within a CSV export, as HTML field content wouldn’t be visible in these.

Note: The code below is meant only for standard input fields (Single Line Text, Email, etc). The best way to prevent input in other fields, such as Dropdown, Checkboxes, or Multiple Choice, is to only provide a single option to the user.

/**
 * Disable form fields to make read-only
 * To apply, add CSS class 'wpf-disable-field' (no quotes) to field in form builder
 *
 */
function wpf_dev_disable_field() {
	?>
	<script type="text/javascript">

		jQuery(function($) {
			$(".wpf-disable-field input").attr("readonly", true);
		});

	</script>
	<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_disable_field' );

After adding this code to your site, you’ll need to identify which fields you’d like to disable.

To do this, open the form builder and click on the field in the preview panel to open its Field Options. Under Advanced Options, you’ll need to add wpf-disable-field to the CSS Classes field.

Add disable CSS class to WPForms field

If using more than one CSS class for a field, just be sure to put a space between each class name.

Next, you’ll need to add a Default Value for your field, which can also be done in this Advanced Options section. This can be regular text or a Smart Tag to pull specific data. If you’d like, you can also check out our tutorial on creating a custom Smart Tag.

Add default value to disabled field

Once this setup is complete, the user will be able to see the default value but will not be able to edit it.

Updated on December 7, 2018

Was this article helpful?