Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add "hidden" field to form?

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.

like image 958
4thSpace Avatar asked Dec 15 '25 06:12

4thSpace


2 Answers

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);
like image 102
baao Avatar answered Dec 16 '25 19:12

baao


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

like image 37
LcSalazar Avatar answered Dec 16 '25 19:12

LcSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!