How to Disable a Form Field to Prevent User Input

Introduction

Would you like to disable a form field to prevent any user input? 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 you place there for default text from being changed by your visitors. In this tutorial, we’ll show you how to disable a form field to prevent any user input.

This could also be helpful when you’d like this value to be included in the {all_fields} Smart Tag for notification emails or within a CSV export.

Creating your form

First, you’ll need to create a new form. For the purpose of this tutorial, we’re going to add a Paragraph Text field that will contain a message with a Smart Tag of today’s date as a date stamp for the form submission.

If you need any help creating your form, please review this tutorial.

Once your form is created, add a Paragraph Text field to your form and on the Advanced tab add wpf-disable-field to the CSS Class Name.

Add the CSS Class Name to the correct field in order to disable a form field

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

Adding the snippet to disable the form field

It’s now time to add the code snippet that will pull this all together.

If you need help in adding code to your site, please see this tutorial.

/**
 * Make standard form fields to make read-only
 * To apply, add CSS class 'wpf-disable-field' (no quotes) to field in form builder
 *
 * @link https://wpforms.com/developers/disable-a-form-field-to-prevent-user-input/
 */

function wpf_dev_disable_field() {
	?>
	<script type="text/javascript">

	jQuery(function($) {

		$( '.wpf-disable-field input, .wpf-disable-field textarea' ).attr({
			 readonly: "readonly",
			 tabindex: "-1"
		});
		
	});

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

The code above will not only disable any form field on any form with the CSS class of wpf-disable-field but will also skip over these fields as the user tabs through each field.

Now your visitors will see the field and the default text you place in it but will not be able to change the field.

The best way to prevent input in other fields, such as Dropdown, Checkboxes, or Multiple Choice would be to only provide a single option to the user.

And that’s all you need to set up your form fields to be read-only. Would you like to change the sublabels on the Name field? Our article on How to Change Sublabels for the Name Field will walk you through the steps on how to accomplish this.

Action Reference: wpforms_wp_footer_end