I use OptimizePress (wordpress theme). It has great opt-in forms but unfortunately, there isn't a way to add a hidden form field through their UI. I do have the option to add custom scripts for each page.
How can I dynamically add a predefined hidden field to a form? The form does not have an ID. Something like the following may work but how can it be done when there is no form ID?
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("formname").appendChild(input);
This is the only form on the page.
Using some of the examples below, it doesn't work with type=hidden: https://jsfiddle.net/eLazhj3d/1.
But works with type=text: https://jsfiddle.net/eLazhj3d/2.
Here's a working fiddle (with a visible text field to show):
Using:
document.querySelector("form").appendChild(input);
https://jsfiddle.net/s55snxtn/
Code: html:
<form action=""><input type="text"/>
</form>
javascript:
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.querySelector("form").appendChild(input);
Using the document.querySelector() function you can target any element using a css selector base, so in your case:
document.querySelector("form").appendChild(input);
Would get any element that is a form tag.
Query Selector Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With