jQuery 如何在提交前向表单添加其他字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17809056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:00:19  来源:igfitidea点击:

How to add additional fields to form before submit?

jqueryhtmlformspostfield

提问by Spook

Is there a way to use javascript and JQuery to add some additional fields to be sent from a HTTP form using POST?

有没有办法使用 javascript 和 JQuery 添加一些额外的字段,以便使用 POST 从 HTTP 表单发送?

I mean:

我的意思是:

<form action="somewhere" method="POST" id="form">
  <input type="submit" name="submit" value="Send" />
</form>

<script type="text/javascript">
  $("#form").submit( function(eventObj) {
    // I want to add a field "field" with value "value" here
    // to the POST data

    return true;
  });
</script>

回答by Suresh Atta

Yes.You can try with some hidden params.

是的。你可以试试一些隐藏的参数。

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

回答by Khawer Zeshan

Try this:

尝试这个:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

回答by de_nuit

$('#form').append('<input type="text" value="'+yourValue+'" />');

回答by Mohammad Adil

You can add a hiddeninputwith whatever value you need to send:

您可以添加一个hiddeninput您需要发送的任何值:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

回答by Jeff Lowery

This works:

这有效:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

回答by Mohamed Allal

May be useful for some:

可能对某些人有用:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(一个允许您使用对象将数据添加到表单的函数,如果有,则覆盖现有输入)[纯 js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

(表单是 dom el,而不是 jquery 对象 [ jqryobj.get(0) 如果需要])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

用 :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

你也可以这样使用它

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

如果您也喜欢,也可以添加 # ("#myformid")。