简体   繁体   English

使用 jQuery 获取表单输入字段?

[英]Obtain form input fields using jQuery?

I have a form with many input fields.我有一个包含许多输入字段的表单。

When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?当我使用 jQuery 捕获提交表单事件时,是否可以在关联数组中获取该表单的所有输入字段?

$('#myForm').submit(function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray :感谢 Simon_Weaver 的提示,这是您可以使用serializeArray另一种方法:

var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
    values[field.name] = field.value;
});

Note that this snippet will fail on <select multiple> elements.请注意,此代码段将在<select multiple>元素上失败。

It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3.新的 HTML 5 表单输入似乎不适用于 jQuery 1.3 版中的serializeArray This works in version 1.4+这适用于 1.4+ 版本

Late to the party on this question, but this is even easier:在这个问题上迟到了,但这更容易:

$('#myForm').submit(function() {
    // Get all the forms elements and their values in one step
    var values = $(this).serialize();

});

The jquery.form plugin may help with what others are looking for that end up on this question. jquery.form插件可能有助于解决其他人正在寻找的最终问题。 I'm not sure if it directly does what you want or not.我不确定它是否直接执行您想要的操作。

There is also the serializeArray function.还有serializeArray函数。

Sometimes I find getting one at a time is more useful.有时我发现一次得到一个更有用。 For that, there's this:为此,有这个:

var input_name = "firstname";
var input = $("#form_id :input[name='"+input_name+"']"); 

Here is another solution, this way you can fetch all data about the form and use it in a serverside call or something.这是另一种解决方案,通过这种方式您可以获取有关表单的所有数据并在服务器端调用或其他事情中使用它。

$('.form').on('submit', function( e )){ 
   var form = $( this ), // this will resolve to the form submitted
       action = form.attr( 'action' ),
         type = form.attr( 'method' ),
         data = {};

     // Make sure you use the 'name' field on the inputs you want to grab. 
   form.find( '[name]' ).each( function( i , v ){
      var input = $( this ), // resolves to current input element.
          name = input.attr( 'name' ),
          value = input.val();
      data[name] = value;
   });

  // Code which makes use of 'data'.

 e.preventDefault();
}

You can then use this with ajax calls:然后,您可以将其与 ajax 调用一起使用:

function sendRequest(action, type, data) {
       $.ajax({
            url: action,
           type: type,
           data: data
       })
       .done(function( returnedHtml ) {
           $( "#responseDiv" ).append( returnedHtml );
       })
       .fail(function() {
           $( "#responseDiv" ).append( "This failed" );
       });
}

Hope this is of any use for any of you :)希望这对你们中的任何人都有用:)

$('#myForm').bind('submit', function () {
  var elements = this.elements;
});

The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.元素变量将包含表单中的所有输入、选择、文本区域和字段集。

This piece of code will work instead of name, email enter your form fields name这段代码将代替名称,电子邮件输入您的表单字段名称

$(document).ready(function(){
  $("#form_id").submit(function(event){
    event.preventDefault();
    var name = $("input[name='name']",this).val();
    var email = $("input[name='email']",this).val();
  });
});

Had a similar issue with a slight twist and I thought I'd throw this out.有一个类似的问题,略有不同,我想我会把它扔掉。 I have a callback function that gets the form so I had a form object already and couldn't easy variants on $('form:input') .我有一个获取表单的回调函数,所以我已经有了一个表单对象,并且在$('form:input')上不容易变体。 Instead I came up with:相反,我想出了:

    var dataValues = {};
    form.find('input').each(
        function(unusedIndex, child) {
            dataValues[child.name] = child.value;
        });

Its similar but not identical situation, but I found this thread very useful and thought I'd tuck this on the end and hope someone else found it useful.它类似但不完全相同的情况,但我发现这个线程非常有用,并认为我会把它放在最后,希望其他人发现它有用。

http://api.jquery.com/serializearray/ http://api.jquery.com/serializearray/

$('#form').on('submit', function() {
    var data = $(this).serializeArray();
});

This can also be done without jQuery using the XMLHttpRequest Level 2 FormData object这也可以在没有 jQuery 的情况下使用 XMLHttpRequest Level 2 FormData 对象完成

http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface

var data = new FormData([form])

Associative?联想? Not without some work, but you can use generic selectors:并非没有一些工作,但您可以使用通用选择器:

var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});

Don't forget the checkboxes and radio buttons -不要忘记复选框和单选按钮 -

var inputs = $("#myForm :input");
var obj = $.map(inputs, function(n, i) {
  var o = {};
  if (n.type == "radio" || n.type == "checkbox")
    o[n.id] = $(n).attr("checked");
  else
    o[n.id] = $(n).val();
  return o;
});
return obj

jQuery's serializeArray does not include disabled fields, so if you need those too, try: jQuery 的serializeArray不包含禁用字段,因此如果您也需要这些字段,请尝试:

var data = {};
$('form.my-form').find('input, textarea, select').each(function(i, field) {
    data[field.name] = field.value;
});

Seems strange that nobody has upvoted or proposed a concise solution to getting list data.似乎很奇怪,没有人赞成或提出一种简洁的解决方案来获取列表数据。 Hardly any forms are going to be single-dimension objects.几乎没有任何形式是单维对象。

The downside of this solution is, of course, that your singleton objects are going to have to be accessed at the [0] index.当然,此解决方案的缺点是您的单例对象必须在 [0] 索引处访问。 But IMO that's way better than using one of the dozen-line mapping solutions.但是 IMO 这比使用十多行映射解决方案之一要好得多。

var formData = $('#formId').serializeArray().reduce(function (obj, item) {
    if (obj[item.name] == null) {
        obj[item.name] = [];
    } 
    obj[item.name].push(item.value);
    return obj;
}, {});

I had the same problem and solved it in a different way.我遇到了同样的问题,并以不同的方式解决了它。

var arr = new Array();
$(':input').each(function() {
 arr.push($(this).val());
});
arr;

It returns the value of all input fields.它返回所有输入字段的值。 You could change the $(':input') to be more specific.您可以将$(':input')更改为更具体。

Same solution as given by nickf , but with array input names taken into account egnickf给出的解决方案相同,但考虑了数组输入名称,例如

<input type="text" name="array[]" />

values = {};
$("#something :input").each(function() {
  if (this.name.search(/\[\]/) > 0) //search for [] in name
  {
    if (typeof values[this.name] != "undefined") {
      values[this.name] = values[this.name].concat([$(this).val()])
    } else {
      values[this.name] = [$(this).val()];
    }
  } else {
    values[this.name] = $(this).val();
  }
});

If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following:如果您需要从输入中获取多个值并且您使用 [] 来定义具有多个值的输入,则可以使用以下内容:

$('#contentform').find('input, textarea, select').each(function(x, field) {
    if (field.name) {
        if (field.name.indexOf('[]')>0) {
            if (!$.isArray(data[field.name])) {
               data[field.name]=new Array();
            }
            data[field.name].push(field.value);
        } else {
            data[field.name]=field.value;
        }
    }                   
});

I am using this code without each loop:我在没有每个循环的情况下使用此代码:

$('.subscribe-form').submit(function(e){
    var arr=$(this).serializeArray();
    var values={};
    for(i in arr){values[arr[i]['name']]=arr[i]['value']}
    console.log(values);
    return false;
});

Inspired by answers of Lance Rushing and Simon_Weaver , this is my favourite solution.受到Lance RushingSimon_Weaver回答的启发,这是我最喜欢的解决方案。

$('#myForm').submit( function( event ) {
    var values = $(this).serializeArray();
    // In my case, I need to fetch these data before custom actions
    event.preventDefault();
});

The output is an array of objects, eg输出是一个对象数组,例如

[{name: "start-time", value: "11:01"}, {name: "end-time", value: "11:11"}]

With the code below,使用下面的代码,

var inputs = {};
$.each(values, function(k, v){
    inputs[v.name]= v.value;
});

its final output would be它的最终输出将是

{"start-time":"11:01", "end-time":"11:01"}

I hope this is helpful, as well as easiest one.我希望这是有帮助的,也是最简单的。

 $("#form").submit(function (e) { 
    e.preventDefault();
    input_values =  $(this).serializeArray();
  });

serialize() is the best method. serialize() 是最好的方法。 @ Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. @ Christopher Parker 说 Nickf 的 anwser 完成的更多,但是它没有考虑到表单可能包含 textarea 和选择菜单。 It is far better to use serialize() and then manipulate that as you need to.使用 serialize() 然后根据需要对其进行操作要好得多。 Data from serialize() can be used in either an Ajax post or get, so there is no issue there.来自 serialize() 的数据可以在 Ajax post 或 get 中使用,所以那里没有问题。

Hope this helps somebody.希望这可以帮助某人。 :) :)

// This html:
// <form id="someCoolForm">
// <input type="text" class="form-control" name="username" value="...." />
// 
// <input type="text" class="form-control" name="profile.first_name" value="...." />
// <input type="text" class="form-control" name="profile.last_name" value="...." />
// 
// <input type="text" class="form-control" name="emails[]" value="..." />
// <input type="text" class="form-control" name="emails[]" value=".." />
// <input type="text" class="form-control" name="emails[]" value="." />
// </form>
// 
// With this js:
// 
// var form1 = parseForm($('#someCoolForm'));
// console.log(form1);
// 
// Will output something like:
// {
// username: "test2"
// emails:
//   0: ".@....com"
//   1: "...@........com"
// profile: Object
//   first_name: "..."
//   last_name: "..."
// }
// 
// So, function below:

var parseForm = function (form) {

    var formdata = form.serializeArray();

    var data = {};

    _.each(formdata, function (element) {

        var value = _.values(element);

        // Parsing field arrays.
        if (value[0].indexOf('[]') > 0) {
            var key = value[0].replace('[]', '');

            if (!data[key])
                data[key] = [];

            data[value[0].replace('[]', '')].push(value[1]);
        } else

        // Parsing nested objects.
        if (value[0].indexOf('.') > 0) {

            var parent = value[0].substring(0, value[0].indexOf("."));
            var child = value[0].substring(value[0].lastIndexOf(".") + 1);

            if (!data[parent])
                data[parent] = {};

            data[parent][child] = value[1];
        } else {
            data[value[0]] = value[1];
        }
    });

    return data;
};

All answers are good, but if there's a field that you like to ignore in that function?所有答案都很好,但是如果该函数中存在您想忽略的字段? Easy, give the field a property, for example ignore_this:很简单,给字段一个属性,例如 ignore_this:

<input type="text" name="some_name" ignore_this>

And in your Serialize Function:在你的序列化函数中:

if(!$(name).prop('ignorar')){
   do_your_thing;
}

That's the way you ignore some fields.这就是您忽略某些字段的方式。

When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked.当我需要对所有表单字段进行 ajax 调用时,我遇到了:input选择器返回所有复选框的问题,无论它们是否被选中。 I added a new selector to just get the submit-able form elements:我添加了一个新的选择器来获取可提交的表单元素:

$.extend($.expr[':'],{
    submitable: function(a){
        if($(a).is(':checkbox:not(:checked)'))
        {
            return false;
        }
        else if($(a).is(':input'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
});

usage:用法:

$('#form_id :submitable');

I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would.我还没有用多个选择框测试过它,但它适用于以标准提交的方式获取所有表单字段。

I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type.我在 OpenCart 站点上自定义产品选项以包含复选框和文本字段以及标准选择框类型时使用了它。

Try the following code:试试下面的代码:

jQuery("#form").serializeArray().filter(obje => 
obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")

For multiple select elements ( <select multiple="multiple"> ), I modified the solution from @Jason Norwood-Young to get it working.对于多个选择元素( <select multiple="multiple"> ),我修改了@Jason Norwood-Young 的解决方案以使其正常工作。

The answer (as posted) only takes the value from the first element that was selected, not all of them .答案(如已发布)仅从选择的第一个元素中获取值,而不是全部 It also didn't initialize or return data , the former throwing a JavaScript error.它也没有初始化或返回data ,前者抛出一个 JavaScript 错误。

Here is the new version:这是新版本:

function _get_values(form) {
  let data = {};
  $(form).find('input, textarea, select').each(function(x, field) {
    if (field.name) {
      if (field.name.indexOf('[]') > 0) {
        if (!$.isArray(data[field.name])) {
          data[field.name] = new Array();
        }
        for (let i = 0; i < field.selectedOptions.length; i++) {
          data[field.name].push(field.selectedOptions[i].value);
        }

      } else {
        data[field.name] = field.value;
      }
    }

  });
  return data
}

Usage:用法:

_get_values($('#form'))

Note: You just need to ensure that the name of your select has [] appended to the end of it, for example:注意:您只需要确保选择的name末尾附加[] ,例如:

<select name="favorite_colors[]" multiple="multiple">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>
$("#form-id").submit(function (e) { 
  e.preventDefault();
  inputs={};
  input_serialized =  $(this).serializeArray();
  input_serialized.forEach(field => {
    inputs[field.name] = field.value;
  })
  console.log(inputs)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM