I found the following code to make a field read-only on a form in WordPress, but I can't figure out how to make it work for two separate forms:
// update '1' to the ID of your form
add_filter( 'gform_pre_render_1', 'add_readonly_script' );
function add_readonly_script( $form ) {
?>
<script type="text/javascript">
jQuery(document).on('gform_post_render', function(){
/* apply only to a input with a class of gf_readonly */
jQuery("#input_1_14_4").attr("readonly","readonly");
});
</script>
<?php
return $form;
}
How can I make this script work with two separate forms and two separate fields? I tried adding the script twice but it broke the site.
Forms: gform_pre_render_1, gform_pre_render_20
Fields: #input_1_14_4, #input_20_14_4
CodePudding user response:
There’s more eloquent ways of doing this, but the most important part is you need to register two filters, one for each form. The callback for the filter can either be a direct function (which I prefer), or a named one, and that’s where your original code was probably breaking, because I’m guess you named your function the same which is not valid in PHP.
The code below creates two uniquely named functions and registers actions for each.
One word of caution, echoing content from a filter is generally not a good idea and might break certain code paths that would assume such a thing wouldn’t happen. That said, apparently that’s how GF recommends doing it so I guess that’s safe, hopefully.
add_filter( 'gform_pre_render_1', 'add_readonly_script_form_1' );
function add_readonly_script_form_1( $form ) {
?>
<script type="text/javascript">
jQuery(document).on('gform_post_render', function(){
/* apply only to a input with a class of gf_readonly */
jQuery("#input_1_14_4").attr("readonly","readonly");
});
</script>
<?php
return $form;
}
add_filter( 'gform_pre_render_20', 'add_readonly_script_form_20' );
function add_readonly_script_form_20( $form ) {
?>
<script type="text/javascript">
jQuery(document).on('gform_post_render', function(){
/* apply only to a input with a class of gf_readonly */
jQuery("#input_20_14_4").attr("readonly","readonly");
});
</script>
<?php
return $form;
}
Alternatively, although I don’t have a copy of WordPress available right now to test this, I think you can skip PHP, Gravity and jQuery completely with this JS. It might need some tweaks for placement, too.
document
.addEventListener(
'gform_post_render',
() => {
document
.querySelectorAll('#input_1_14_4, #input_20_14_4')
.forEach(
(field) => {
field.setAttribute('readonly', 'readonly');
}
)
;
}
)
;