I have been working off of these two answers:
WordPress Contact Form 7 dynamically select dropdown field based on url
Auto-select fields in Contact form 7 based on referral link
Currently, the code below is pasted in the CSS block on the /contact page:
(function($){
$(document).ready(function() {
//determine the previous page,
let page = document.referrer, opt='';
switch(true){
case page.indexOf(’douglas-h-flint’)>0:
opt=‘douglashflint’;
break;
case page.indexOf(‘john-f-connolly’)>0:
opt=‘johnfconnolly’;
break;
case page.indexOf(‘david-l-walker-jr’)>0:
opt=‘davidlwalkerjr’;
break;
}
$('select[name=“select-recipient”]’).find('option[value="'+opt+'"]').prop('selected', 'selected');
})
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="select-recipient”>
<option value="">General Inquiry</option>
<option value=“douglashflint”>Douglas H. Flint</option>
<option value=“johnfconnolly”>John F. Connolly</option>
<option value=“davidlwalkerjr”>David L. Walker, Jr.</option>
</select>
My website is: https://c7n.f22.myftpupload.com/
My goal is that when someone navigates to the /contact page directly from one of these people’s individual pages—(/attorneys/douglas-h-flint) or (/attorneys/john-f-connolly) or (/attorneys/david-l-walker-jr)—that the "Inquire with:" dropdown field in the contact form would autoselect their respective name and that when someone navigates to the /contact page from any other page on the site, the "Inquire with:" dropdown field would remain defaulted to "General Inquiry" option.
What am I missing? Or what am I doing incorrectly?
Thank you in advance for any help!
2
Answers
Watch the funny stylish quotes (
‘
,’
,“
and”
) that you have. Those will break JS. Remove them from the HTML markup and CSS as well.Beyond that, the expected value for the second argument of the
.prop()
method is a boolean (true
orfalse
), so that would be:Finally, it is quite scary to read the code below is pasted in the CSS block… Place this code inside the
<head>
tag of the page:While the other answer is a good answer, it’s not quite WordPress useable as is. Since this is contact form 7, and WordPress, there are a few things wrong with it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
the jQuery library is already included with WordPress.no conflict
mode, so you have to initialize first withjQuery
and not$
wp_add_inline_script
to properly enqueue your script conditionally.So if you add the following to your contact form… it will work.