TAGS :Viewed: 3 - Published at: a few seconds ago

[ How can I send a variable to a form using this javascript function? ]

I've got this onclick call:


which calls this function:

function mySubmit(){

which then submits this form:

<form id="myForm" action="action.php" method="post">

My question is: how do I send a variable to the form from the onClick to get something like <form id="myForm" action="action.php?id=**(the variable sent from the onclick goes here)**" method="post">


Answer 1

Easiest way: append a hidden field to the form.

<form id="myForm" action="action.php" method="post">
  <input type='hidden' id= 'hiddenField' name='id' value='' />

  function mySubmit() {
     document.getElementById('hiddenField').value = "Whatever I want here";

Or use a function like

function addHiddenField(form, props) {
  Object.keys(props).forEach(fieldName => {
    var field = form[fieldName];
    if (!field) {
      field = document.createElement('input');
      field.type = 'hidden';
      field.name = fieldName;
    field.value = props[fieldName];

document.querySelector('form').addEventListener('submit', () => {
  addHiddenField(this, {
    someQueryName: 'someQueryValue',
    otherQueryName: 'otherVal'
  <input name=name />
  <input type=submit />

Note that you can use DevTools to modify the iframe's sandbox to allow it to submit forms and you can verify the posted URL. sandbox="... allow-forms"

Answer 2

place a input type hidden inside the form then submit the form

<input id="id" name="id" type="hidden" />

set the value of the hidden field in your javascript submit()

document.getElementById('id').value = **;

but by setting form method="post" the id will not be the part of query string, i.e. the url will remain action.php instead if you really want the id in query string i.e. url action.php?id=** then you need to change the form method="get", by this the hidden field id will automatically be the part of the url i.e action.php?id=**

read about difference between get and post

here is how you access posted value on next page if you really need to use method="post" action="action.php"

Answer 3

Your HTML :

<form id="myForm" action="#" method="post">
            <input type='hidden' id="id" name='id' value='123' />
            <input type='submit' name='submit' value='Click me !' onclick='addParam()' />

Your Script :

function addParam() {

                var url = "action.php?id=" + document.getElementById('id').value;
                document.getElementById("myForm").setAttribute('action', url);


Thank You.