React Comment Section Character Counter - javascript

Hey fellow developers,
so, I'm having this issue with React, and although I think I'm getting to show the 2000 as a number and a value overall, when I write inside the comment section, the number changes to NaN. I tried using the parseInt() in order to turn the span into a number, but nothing happens... Any suggestions?
Here's the code :)
import React from "react";
import Header from "../Header";
import "./contact-form.css";
function characterCounter() {
let text = document.getElementById("message").value;
let textLength = text.length;
let counter = document.getElementById("characterCounter");
let counterNumber = parseInt(counter);
counter.textContent = counterNumber - textLength;
}
class ContactPage extends React.Component {
render() {
return (
<div>
<Header />
<h1>Contact.</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..." />
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..." />
<label>Your Email</label>
<input type="text" placeholder="Email..." />
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onKeyDown={characterCounter}
></textarea>
<span>
Max words <span id="characterCounter">2000</span>
</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
}
export default ContactPage;

So... you are using React, don't you? Well I will rewrite the component to solve the issue in the React's way
const MAX_CHARS = 2000
function ContactPage() {
const [charsLeft, setCharsLeft] = useState(0);
const updateCharsCount = ({target:{value}}) => {
setCharsLeft(MAX_CHARS - value)
}
return (
<div>
<Header/>
<h1>Contact</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..."/>
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..."/>
<label>Your Email</label>
<input type="text" placeholder="Email..."/>
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onChange={updateCharsCount}
></textarea>
<span>Max words {charsLeft}/{MAX_CHARS}</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
export default ContactPage;
By the way, I've used functional component instead of class component, it's the current approach

Related

How to make an error message for each empty form field

I am trying to display an error message for each empty field, my problem is that when I submit the form with an empty (one or two) field all the error messages appear. I want only one error message for each empty field to appear, not all of them.
HTML :
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
JavaScript:
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const password = document.getElementById("password");
if(firstName.value < 1 ) {
errorField.forEach((f) => f.classList.toggle('error-active'));
errorField.forEach((c) => c.style.color = "red");
firstName.classList.toggle("invalid");
return false;
}
if (lastName.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
lastName.classList.toggle("invalid");
return false;
}
if (email.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
email.classList.toggle("invalid");
return false;
}
if (password.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
password.classList.toggle("invalid");
return false;
} else {
password.classList.remove("invalid");
errorField.classList.remove("error-active");
}
return true;
}
submitButton.addEventListener('click' , validate);
Hope this fixed your issue. Notice, password changed to passwordD and you were accessing all the error field without specifying which
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const passwordD = document.getElementById("password");
if (firstName.value < 1) {
errorField[0].classList.toggle('error-active');
errorField[0].style.color = "red";
firstName.classList.toggle("invalid");
}
if (lastName.value < 1) {
errorField[1].classList.toggle("error-active");
errorField[1].style.color = "red";
lastName.classList.toggle("invalid");
}
if (email.value < 1) {
errorField[2].classList.toggle("error-active");
errorField[2].style.color = "red";
email.classList.toggle("invalid");
}
if (password.value < 1) {
errorField[3].classList.add("error-active");
errorField[3].style.color = "red";
passwordD.classList.toggle("invalid");
} else {
passwordD.classList.remove("invalid");
errorField.forEach((f) => {
f.classList.remove("error-active");
f.style.color = "black";
});
return true;
}
return false;
}
submitButton.addEventListener('click', validate);
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
I would suggest you to use a form validation JS plugin instead of reinveting the wheel, for example Form Validation Plugin
You can simplify your code a bit using a class for the inputs, and keeping track of an isValid boolean for the form. You were setting all error-fields with your code. Here, we are able to reference just the error-field that applies using closest() to find the encompassing label, then querySelector to find the error-field
el.closest('label').querySelector('.error-field');
const submitButton = document.querySelector('.form-button');
const validate = (e) => {
e.preventDefault();
let isValid = true
document.querySelectorAll('.validate').forEach(el => {
let error = el.closest('label').querySelector('.error-field').classList;
if (el.value.trim().length === 0) {
isValid = false;
error.add('error-active');
el.classList.add('invalid')
} else {
error.remove('error-active');
el.classList.remove('invalid')
}
})
return isValid;
}
submitButton.addEventListener('click', validate);
.error-field.error-active,
input.invalid{
color: #f00;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" class='validate' name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" class='validate' name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" class='validate' name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" class='validate' name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
That's because inside each if statement you are looping through all the Error fields in the form and update it all. So what you can do is first add unique id for each dom entry in the HTML file such as err-password, error-name and so on then inside each if statement grab the relevant eror field that needs to show the error and update only that field.
Using nextElementSibling would simplify your code a lot here... Since the error message always is right after the input.
In the condition to show or not the error.. That is the value.length you have to check.
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
// Remove any already displayed error
errorField.forEach(function(error){
error.classList.remove("invalid");
})
// Loop through all inputs to check the value length
document.querySelectorAll("form input").forEach(function(input){
if(input.value.length < 1){
input.nextElementSibling.classList.toggle("invalid");
}
})
// Prevent submit only if there are errors shown
let errorCount = document.querySelectorAll(".error-field.invalid").length
if(errorCount){
e.preventDefault();
}
}
submitButton.addEventListener('click' , validate);
label{
display: block;
}
label p{
margin: 0;
}
.error-field{
display: none;
color: red;
}
.invalid{
display: inline-block;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>

How to disable submit button until all input classes have class="valid"

I want to create a sign-up form. I have 6 inputs: First Name, Last Name, E-mail, Password, Password confirmation and a checkbox for user agreement. If inputs have class="valid", value is valid, otherwise invalid. I put all the classes a default class="invalid". I want to disable my submit button until all input fields have class="valid". According to my research, I saw that the button should be disabled first using the window.onload eventlistener, but I still couldn't figure out how to do it.
This is the basic form:
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
I am controlling checkbox validation with an eventlistener:
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
})
And for the rest, i am checking with regexs:
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value])
})
})
Something like this might come in handy.
var form = document.querySelector('.signup__form'), is_valid = false, fields, button;
form.addEventListener('change', function(){
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if( fields[i].classList.contains('invalid') )
{
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled'): button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Since you don't have all of your code, I'm adding a second example myself so that I can fully test the validation part.
But you just need to copy the above JavaScript code and set the button to disabled="disabled"in the first place.
var form = document.querySelector('.signup__form'),
is_valid = false,
fields, button;
form.addEventListener('change', function() {
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if (fields[i].value.length) {
fields[i].classList.remove('invalid');
} else {
fields[i].classList.add('invalid');
}
if (fields[i].classList.contains('invalid')) {
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled') : button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name" /> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Note: This example does not follow because it does not validate the Checkbox.
#Enes, 1. kod parçacığındaki JavaScript kodunu kopyalarsan çalışacaktır. 2. Kodu test edebilmen için ekledim. Bir değer girilmişse onu doğru "valid" kabul eder.
I would try to the native use of HTML properties (pattern & required) and CSS instead of giving in to javascript. Just give it a go, and see how it feels like. Do note that I excluded a pattern on your email input.
The only thing I would use javascript for is to check if the password fields are the same, but I would do that by injecting the password of the first password input into the confirming password input's pattern attribute, replacing ^[\w#-]{8,20}$.
The pink background is just there to show-case the validation rules.
By the way, you got the wrong formatting on some of the HTML tags. You don't need an ending slash on input and you should type <br/>, not </br>.
input:invalid {
background-color: pink;
}
form:invalid button[type="submit"] {
opacity: 0.5;
}
<form class="signup__form" action="/">
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Name"> <br/>
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Last Name"><br/>
<input type="email" required placeholder="E-mail"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password Confirm"><br/>
<input type="checkbox" required>User Agreement<br/>
<button type="submit" >Sign Up</button>
</form>
you can use required="required", then the submit won't be called before the field has value.
A solution which tests the number of invalid classes:
var checkbox = document.querySelector("input[type=checkbox]");
var inputs = document.querySelectorAll("input:not([type='checkbox'])");
var but = document.querySelector("button[type=submit]");
but.disabled= true;
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value]);
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
})
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
We will use couple of properties to validate the form which are required, pattern, disabled and also we will use CSS properties to control the form validation
input:invalid {
background-color: red;
}
form:invalid input[type="submit"] {
opacity: 0.5;
cursor: not-allowed;
}
<form class="login__form" action="/">
<input type="email" required placeholder="E-mail"><br/><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/><br/>
<input type="submit" >
</form>

Why is my button color not changing on command?

I "made" this script:
<script>
export default {
name: "Form"
}
var backRGB = document.getElementById("color").value;
document.getElementById("color").onchange = function() {
backRGB = this.value;
console.log(backRGB);
document.getElementById("orgButton").color = backRGB;
}
</script>
It supposedly checks if the color picker with 'color' has changed and if it does it changes the button 'orgButon' to the color that was picked. However, it's not working. I think that even the console.log isn't working.
Here's the template:
<template>
<div>
<div class="formulario">
<h1>Criar Organização</h1>
<form>
<div><input class="long" type="text" name="orgName" id="orgName" placeholder="Nome" minlength="5" maxlength="20"></div>
<div>
<input class="short" type="text" name="orgAbb" id="orgAbb" placeholder="Abreviatura" minlength="3" maxlength="4">
<input type="color" id="color" value="#f6b73c">
</div>
<input class="button" type="button" id="orgButton" value="Criar">
</form>
</div>
</div>
</template>
The code above is all in Form.vue.
If the JS is above the HTML, it will fail because document.getElementById("color") doesn't exist yet so it can't set its onchange event handler.
The following code worked for me:
<div>
<div class="formulario">
<h1>Criar Organização</h1>
<form>
<div><input class="long" type="text" name="orgName" id="orgName" placeholder="Nome" minlength="5" maxlength="20"></div>
<div>
<input class="short" type="text" name="orgAbb" id="orgAbb" placeholder="Abreviatura" minlength="3" maxlength="4">
<input type="color" id="color" value="#f6b73c">
</div>
<input class="button" type="button" id="orgButton" value="Criar">
</form>
</div>
</div>
<script>
var backRGB = document.getElementById("color").value;
document.getElementById("color").onchange = function() {
backRGB = this.value;
console.log(backRGB);
document.getElementById("orgButton").style.backgroundColor = backRGB;
}
</script>
I see you are using vue.js in your code. This solution makes use of two-way binding with v-model
<template>
<div id="app">
<input type="color" v-model="color">
<p>{{ color }}</p>
<button :style="{color}">BUTTON</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
color: ""
};
},
};
</script>
Open this codepen for demonstration
EDIT: more info on reactive styles here

I want to store input data in object but can't be able to do so?

html
<form name="AdminForm" onsubmit="return Updateit()">
<input type="text" id="name" required>
<input type="email" id="email" required>
<input type="number" id="phoneNumb" required>
<input type="text" id="address" required>
<input type="submit" value="Submit" class="btn">
<input type="reset" value="Reset">
</form>
Javascript
var database = {}
function Updateit(){
const Name = document.forms["AdminForm"]["name"].value;
const Email = document.forms["AdminForm"]["email"].value;
const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
const Address = document.forms["AdminForm"]["address"].value;
database[Name] = [Email,PhoneNumb.toString(),Address];
console.log(database[Name]);
}
the data in object is vanished after a Millisecond
After input data in form i used to save that data in database object but is not shown in it when i try to display in console or alert.
You have not specified your Html structure and when this function was triggered, but if so, what is the problem with its operation ?
var database = {}
let button = document.getElementById("get-form");
button.addEventListener("click", Updateit)
function Updateit() {
const Name = document.forms["AdminForm"]["name"].value;
const Email = document.forms["AdminForm"]["email"].value;
const PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
const Address = document.forms["AdminForm"]["address"].value;
database[Name] = [Email, PhoneNumb.toString(), Address];
console.log(database[Name]);
}
<form name="AdminForm">
<input type="text" name="name">
<input type="email" name="email">
<input type="text" name="phoneNumb">
<input type="text" name="address">
<button type="button" id="get-form">Get Form Items</button>
</form>
var database = {}
database.Name = document.forms["AdminForm"]["name"].value;
database.Email = document.forms["AdminForm"]["email"].value;
database.PhoneNumb = document.forms["AdminForm"]["phoneNumb"].value;
database.Address = document.forms["AdminForm"]["address"].value;
function Updateit(){
console.log(database[Name]);
}
}

Script to push UTM values from URL to hidden fields (Webflow)

I just released our new website in Webflow, but there is no easy way to collect UTM values from the URL and push them to the form fields. I created the 5 UTM hidden fields (UTM Medium, UTM Source, UTM Campaign, UTM Content, UTM Term). Now I need to add a HTML code to the page to push the values from the URL.
I was given this script:
<script>
const urlParams = new URLSearchParams(window.location.search);
const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
let utmFieldValue = '';
utmParams.forEach(function (param) {
const paramValue = urlParams.get(param);
if (paramValue) {
utmFieldValue += `${param}=${paramValue} `
}
});
const utmField = document.getElementById('utm-field');
utmField.value = utmFieldValue.trim();
</script>
However, it looks like all the values are pushed into one single field. Can anyone rewrite this script to reflect that each value should be added to the right field?
This is an example of a URL with UTMs: google.com/?utm_source=crowdcast&utm_medium=webinar&utm_campaign=blog&utm_content=how-we-use-linkedin-ads
The URL where the form lives is https://saasmql.com/contact-us
This is the code for the form:
<html>
...
<div id="w-node-07aa8d855a85-8d855a85" class="form-wrap">
<h2 class="h2 center white">Book an Intro Call</h2>
<div>
<div class="w-form">
<form id="wf-form-Contact-Us-Form" name="wf-form-Contact-Us-Form" data-name="Contact Us Form"
redirect="/thank-you" data-redirect="/thank-you">
<input type="text" class="text-field w-input" maxlength="256" name="First-2" data-name="First 2"
placeholder="First Name" id="First-2" required="" />
<input type="text" class="text-field w-input" maxlength="256" name="Last-2" data-name="Last 2"
placeholder="Last Name" id="Last-2" required="" />
<input type="email" class="text-field w-input" maxlength="256" name="email-2" data-name="Email 2"
placeholder="Email Address" id="email-2" required="" />
<input type="text" class="text-field w-input" maxlength="256" name="Company-2" data-name="Company 2"
placeholder="Company" id="Company-2" required="" />
<input type="text" class="text-field w-input" maxlength="256" name="Job-Title-3" data-name="Job Title 3"
placeholder="Job Title" id="Job-Title-3" required="" />
<textarea placeholder="Comments" maxlength="5000" id="Comments-2" name="Comments-2"
data-name="Comments 2" class="text-field w-input">
</textarea>
<input type="text" class="text-field-utm w-input" maxlength="256" name="utm_source"
data-name="utm_source" placeholder="UTM Source" id="utm_source" />
<input type="text" class="text-field-utm w-input" maxlength="256" name="utm_campaign"
data-name="utm_campaign" placeholder="UTM Campaign" id="utm_campaign-2" />
<input type="text" class="text-field-utm w-input" maxlength="256" name="Utm-Content"
data-name="Utm Content" placeholder="UTM Content" id="Utm-Content-2" />
<input type="text" class="text-field-utm w-input" maxlength="256" name="Utm-Term" data-name="Utm Term"
placeholder="UTM Term" id="Utm-Term-3" />
<input type="submit" value="SUBMIT" data-wait="Please wait..." class="blue-button full-size w-button" />
</form>
</div>
</div>
</div>
...
</html>
This should work
const urlParams = new URLSearchParams(window.location.search);
const utmParams = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content'
];
let paramValue, utmField;
utmParams.forEach(function (param) {
paramValue = urlParams.get(param);
utmField = document.querySelector("input[name='"+param+"']");
if (paramValue && utmField) {
utmField.value = paramValue.trim();
}
});
Make sure to have all your fields strictly follow this naming:
utm_source
utm_medium
utm_campaign
utm_term
utm_content

Categories

Resources