Search code examples
jqueryhtmlcsswordpresscontact-form-7

How to place label inside the span element wpcf7-form-control-wrap


I would like to put the label for input elements inside the span element generated by the cf7 shortcode - is thi spossible?

The reason I want to do this is that I am trying to make the label only appear when the input field has :focus

In order to do this the label and the input need to be inside the same element so I can target with the following css selector:

input-ID:focus + .label-class

I have tried just pasting the generated HTML markup into CF7 and moving the label inside (rather than using the shortcode) which acheives what I want, however it causes a strange problem where the "required" attribute no longer works - all fields are required but the form can now be submitted empty

This is what CF7 Generates:

<span class="wpcf7-form-control-wrap your-name-wrap">
<input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="your-name-1" aria-required="true" aria-invalid="false" placeholder="Name"></span>
<label for="your-name" class="label-helper">Name</label>

This is what I want:

<span class="wpcf7-form-control-wrap your-name-wrap">
<input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="your-name-1" aria-required="true" aria-invalid="false" placeholder="Name">
<label for="your-name" class="label-helper">Name</label></span>

I've tried implementing the HTML above rather than using CF7 shortcode but required no longer works


Solution

  • Please check it may it will help. I think you used in each function or through loop..

    var getLabel = $(".wpcf7-form-control-wrap").next("label").detach();
            $(".wpcf7-form-control-wrap").append(getLabel);
    .wpcf7-form-control:focus + .label-helper{color: red;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="wpcf7-form-control-wrap your-name-wrap">
    <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" id="your-name-1" aria-required="true" aria-invalid="false" placeholder="Name"></span>
    <label for="your-name" class="label-helper">Name</label>