I want to give buttons a data-attribute. Then I want to set the input value through javascript.
Basically if someone clicks on one of five buttons (starter,bronze,silver,gold,platin) he gets to the contact form with the value (s,b,s,g,p) already in the form (input value).
I’ve searched a lot on stack overflow and there is a lot. But I couldn’t quite put 1 and 1 together, probably it’s just me.
To solve this would take a 2 step approach as your packages and contact pages are separate. So first step is that when someone clicks one of the buttons on the packages page, to route them to the contact page with an attribute in the url. So something like /contact?package=s.
So instead of this:
Do this:
Then once the user lands on the contact page, you need a script to check if the URL has any query parameters set. If it detects that there is a value for packages, e.g /contact?packages=s, then to set the value for the packages field in the form. You will need to modify the sample script below to suit your exact use case but in any case it should give you a good idea of how to do this. You would put this script into the body code of the contact page.
<script>
// Check the URL for the "package" parameter
const urlParams = new URLSearchParams(window.location.search);
const package = urlParams.get('package');
// If this exists then set the field value
if (package) {
// Make a reference to the package dropdown field in the form
const packageField = document.getElementById('package-field');
// Set the value of the dropdown
switch (package) {
case 's1':
packageField.value = 's1';
break;
case 'b':
packageField.value = 'b';
break;
case 's2':
packageField.value = 's2';
break;
case 'g':
packageField.value = 'g';
break;
case 'p':
packageField.value = 'p';
break;
}
}
</script>
I also tried to put in into the head code but that didn’t work either.
The only thing I added - instead of editing - is the last tag because the site wouldnt load at all if it wasn’t
From what I can see, the issue is that this code is executed before the form exists on the page. You have the code in a code embed element above the form itself.
I would move the code snippet to the footer code section of the contact page itself. I just tested this and it works fine. Your script itself is working.
Hey @jasondark and @Tim_Leon_Cruse, great team work! I was looking for this exact functionality for one of my projects. Would it be possible to post the full custom javascript in the forum?