Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 999
NCoder Avatar asked Jan 31 '11 19:01

NCoder


1 Answers

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"

like image 171
Juan Mendes Avatar answered Oct 26 '22 05:10

Juan Mendes