如何使用此javascript函数将变量发送到表单? [英] How can I send a variable to a form using this javascript function?

查看:67
本文介绍了如何使用此javascript函数将变量发送到表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个onclick电话:

I've got this onclick call:

onClick="mySubmit();

调用此函数:

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

然后提交此表单:

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

我的问题是:怎么做我从onClick向表单发送一个变量,得到类似< form id =myFormaction =action.php?id = **(从onclick发送的变量在这里)* *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">

谢谢!

推荐答案

最简单的方法:在表单中添加隐藏字段。

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>

或者使用像

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>

请注意,您可以使用DevTools修改iframe的沙箱以允许其提交表单,并且您可以验证发布的URL。 sandbox =... allow-forms

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"

这篇关于如何使用此javascript函数将变量发送到表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆