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

43,311

Solution 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='' />

<script> 
  function mySubmit() {
     document.getElementById('hiddenField').value = "Whatever I want here";
     document.getElementById("myForm").submit();
   }
</script>

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;
      form.appendChild(field);
    }
    field.value = props[fieldName];
  });
}

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

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"

Solution 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"

Share:
43,311
NCoder
Author by

NCoder

Updated on February 27, 2020

Comments

  • NCoder
    NCoder about 4 years

    I've got this onclick call:

    onClick="mySubmit();
    

    which calls this function:

    function mySubmit(){
        document.getElementById("myForm").submit();
    }
    

    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">

    Thanks!