1

I need to be be able to auto populate a text field with "one-hidden" when a customer checks a checkbox but so far examples I've found online do not seem to work or im putting them in the wrong place.

$('#flight-include').change(function(){
    $("#one-control").text("");
    if ($('#flight-include').is(':checked')) { 
        $("#one-control").text("one-hidden"); 
    }
});

I put the above in the function file and it did nothing so guessing im doing something wrong or missing something.

flight-control is the checkbox, one-control is the text field. "one-hidden" is the text that needs to appear in the text field when the flight-include box is checked.

Can someone help as im pretty clueless with this type of coding. Many thanks

Tried executing the code above in the function file but possible not the right place.

2 Answers 2

1

assuming it is input text field, changing a text field should use

$("#one-control").val("one-hidden");

2
  • Thanks. I made the change but now get the following error in function.php syntax error, unexpected token "[", expecting variable or "{" or "$"
    – Tom Kidd
    Commented May 14, 2023 at 8:41
  • Using your code in the question, just replace .text with .val Commented May 24, 2023 at 1:40
0

You are not showing all of the code, in particular how you are trying to get this to work in your functions.php file. There are a few ways to include custom Javascript code, but in using functions.php, make sure you are doing something like the following, in this case hooking into the wp_head action hook:

function cf7_custom_javascript() {
?>
<script>
// your javascript code goes here
</script>
<?php
}
add_action('wp_head', 'cf7_custom_javascript');

UPDATE: It turns out with CF7 you can't target a checkbox by its ID or class, since according to the documentation it applies the ID and/or class to the element wrapper (span tag). You can target the element directly, but that may only work if it's the only checkbox on the form or you may be able to target by some other attribute, like name.

The sample code below works, but only if there is just one checkbox on the form:

jQuery(document).ready(function() {
    $('input[type="checkbox"]').on('change', function() {
        if (this.checked) {
            $('#one-control').val("one-hidden");
        } else {
            $('#one-control').val("");
        }
    });
});

(note the wrapper used since I've run into issues with using jQuery in my set up)

You should still use the example I provided above in your functions.php file or in a custom plugin.

1
  • Thanks but unfortunately that changes nothing in CF7.
    – Tom Kidd
    Commented May 15, 2023 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.