Organizational Research By

Surprising Reserch Topic

obtain form input fields using jquery


obtain form input fields using jquery  using -'javascript,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?
    

asked Sep 9, 2015 by rajesh
0 votes
6 views



Related Hot Questions

17 Answers

0 votes
$('#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:

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

Note that this snippet will fail on

0 votes

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();

});
answered Sep 9, 2015 by rajesh
0 votes
$('#myForm').bind('submit', function () {
  var elements = this.elements;
});

The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.

answered Sep 9, 2015 by rajesh
0 votes

The jquery.form plugin may help with what others are looking for that end up on this question. I'm not sure if it directly does what you want or not.

There is also the serializeArray function.

answered Sep 9, 2015 by rajesh
0 votes

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 "']"); 
answered Sep 9, 2015 by rajesh
0 votes

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'). 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.

answered Sep 9, 2015 by rajesh
0 votes

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;
});
answered Sep 9, 2015 by rajesh
0 votes

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
answered Sep 9, 2015 by rajesh
0 votes

jQuery's serializeArray does not include disabled fields, so if you need those too, try:

var data = {};
$('form.my-form').find('input, textarea, select').each(function(i, field) {
    data[field.name] = field.value;
});
answered Sep 9, 2015 by rajesh
0 votes

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.

answered Sep 9, 2015 by rajesh
0 votes

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

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

var data = new FormData([form])
answered Sep 9, 2015 by rajesh
0 votes

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;
        }
    }                   
});
answered Sep 9, 2015 by rajesh
0 votes

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

answered Sep 9, 2015 by rajesh
0 votes

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:

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 :)

answered Sep 9, 2015 by rajesh
0 votes

Same solution as given by nickf, but with array input names taken into account eg

            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();
                }
            });
answered Sep 9, 2015 by rajesh
0 votes

serialize() is the best method. @ 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. It is far better to use serialize() and then manipulate that as you need to. Data from serialize() can be used in either an Ajax post or get, so there is no issue there.

answered Sep 9, 2015 by rajesh
0 votes

Hope this helps somebody. :)

// This html:
// 
// 
// 
// 
// 
// 
// 
// 
// 
// 
// 
// 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;
};
answered Sep 9, 2015 by rajesh

...