Uzyskać pola wprowadzania formularza za pomocą jQuery?

Mam formularz z wieloma polami wprowadzania.

Kiedy przechwycę Zdarzenie wyślij formularz za pomocą jQuery, czy możliwe jest pobranie wszystkich pól wejściowych tego formularza w tablicy asocjacyjnej?

Author: Dave Jarvis, 2008-10-04

26 answers

$('#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();
    });

});

Dzięki końcówce od Simon_Weaver, oto inny sposób, w jaki możesz to zrobić, używając serializeArray:

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

Zauważ, że ten fragment zawiedzie na elementach <select multiple>.

Wygląda na to, że nowe wejścia formularza HTML 5 nie działają z serializeArray w jQuery w wersji 1.3. Działa to w wersji 1.4 +

 540
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-23 23:01:01

Spóźnienie na imprezę na to pytanie, ale to jest jeszcze łatwiejsze:

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

});
 258
Author: Lance Rushing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 15:12:12

Jquery.wtyczka form może pomóc w tym, czego szukają inni, co kończy się na tym pytaniu. Nie jestem pewien, czy robi to, co chcesz, czy nie.

Istnieje również funkcja serializeArray .

 23
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-23 02:31:40

Czasami uważam, że kupowanie po kolei jest bardziej przydatne. Do tego jest to:

var input_name = "firstname";
var input = $("#form_id :input[name='"+input_name+"']"); 
 16
Author: Malachi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-24 09:50:21
$('#myForm').bind('submit', function () {
  var elements = this.elements;
});

Zmienna elements będzie zawierać wszystkie wejścia, selekcje, pola tekstowe i pola w formularzu.

 12
Author: Quentin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-04 08:11:38

Oto inne rozwiązanie, w ten sposób możesz pobrać wszystkie dane o formularzu i użyć ich w wywołaniu serwera lub coś takiego.

$('.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();
}

Możesz użyć tego przy wywołaniach 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" );
       });
}

Mam nadzieję, że to się przyda każdemu z Was :)

 12
Author: Ole Aldric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-27 17:27:13

Miałem podobny problem z lekkim skręceniem i pomyślałem, że to wyrzucę. Mam funkcję wywołania zwrotnego, która pobiera formularz, więc miałem już Obiekt formularza i nie mogłem łatwo wybrać $('form:input'). Zamiast tego wymyśliłem:

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

To podobna, ale nie identyczna sytuacja, ale uznałem ten wątek za bardzo przydatny i pomyślałem, że schowam to na końcu i mam nadzieję, że ktoś inny uzna to za przydatne.

 6
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-08 16:02:33

Http://api.jquery.com/serializearray/

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

Można to również zrobić bez jQuery przy użyciu obiektu FormData poziomu 2 XMLHttpRequest

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

var data = new FormData([form])
 5
Author: Chris Wheeler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-10 11:50:51

Asocjacyjny? Nie bez pracy, ale można użyć selektorów generycznych:

var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});
 4
Author: Oli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-04 02:06:56

JQuery serializeArray nie zawiera wyłączonych pól, więc jeśli ich potrzebujesz, spróbuj:

var data = {};
$('form.my-form').find('input, textarea, select').each(function(i, field) {
    data[field.name] = field.value;
});
 4
Author: Sarah Vessels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-27 14:03:36

Nie zapomnij o polach wyboru i przyciskach opcji -

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
 4
Author: Man Called Haney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-10 14:11:37

Ten fragment kodu zadziała zamiast nazwy, e-mail Wpisz swoje pola formularza nazwa

$(document).ready(function(){
  $("#form_id").submit(function(event){
    event.preventDefault();
    var name = $("input[name='name']",this).val();
    var email = $("input[name='email']",this).val();
  });
});
 4
Author: sparsh turkane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-12 07:43:55

Wydaje się dziwne, że nikt nie przegłosował ani nie zaproponował zwięzłego rozwiązania, aby uzyskać dane listy. Prawie żadne formy nie będą obiektami jednowymiarowymi.

Minusem tego rozwiązania jest oczywiście to, że Twoje obiekty singleton będą musiały być dostępne w indeksie [0]. Ale IMO to o wiele lepsze niż korzystanie z jednego z kilkunastu rozwiązań mapowania liniowego.

var formData = $('#formId').serializeArray().reduce(function (obj, item) {
    if (obj[item.name] == null) {
        obj[item.name] = [];
    } 
    obj[item.name].push(item.value);
    return obj;
}, {});
 3
Author: Ryanman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-31 20:44:10

Miałem ten sam problem i rozwiązałem go w inny sposób.

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

Zwraca wartość wszystkich pól wejściowych. Możesz zmienić $(':input'), aby być bardziej szczegółowym.

 2
Author: suizo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-05 08:59:10

Takie samo rozwiązanie jak podane przez nickf , ale z uwzględnieniem nazw wejściowych tablicy eg

<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();
  }
});
 2
Author: Itako,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-10 14:10:31

Jeśli chcesz uzyskać wiele wartości z wejść i używasz [] do definiowania wejść z wieloma wartościami, możesz użyć następującego polecenia:

$('#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;
        }
    }                   
});
 1
Author: Jason Norwood-Young,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-19 09:40:15

Zainspirowany odpowiedziamiLance Rushing iSimon_Weaver , jest to moje ulubione rozwiązanie.

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

Wyjściem jest tablica obiektów, np.

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

Z poniższym kodem,

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

Jego ostateczny wynik to

{"start-time":"11:01", "end-time":"11:01"}
 1
Author: T.Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 17:53:45

Używam tego kodu bez każdej pętli:

$('.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;
});
 1
Author: Roman Grinev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 17:30:27

Mam nadzieję, że jest to pomocne, a także najłatwiejsze.

 $("#form").submit(function (e) { 
    e.preventDefault();
    input_values =  $(this).serializeArray();
  });
 1
Author: dipenparmar12,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-25 12:57:25

Kiedy musiałem wykonać wywołanie ajax ze wszystkimi polami formularza, miałem problemy z selektorem :input zwracającym wszystkie pola wyboru, niezależnie od tego, czy zostały zaznaczone. Dodałem nowy selektor, aby po prostu uzyskać Elementy formularza submit-able:

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

Użycie:

$('#form_id :submitable');

Nie testowałem go jeszcze z wieloma polami wyboru, ale działa na uzyskanie wszystkich pól formularza w sposób standardowy.

Użyłem tego podczas dostosowywania opcji produktu na OpenCart witryna zawierająca pola wyboru i pola tekstowe, a także standardowy typ pola wyboru.

 0
Author: slarti42uk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-05 13:14:10

Serialize() jest najlepszą metodą. @ Christopher Parker mówią, że anwser Nickf osiąga więcej, jednak nie bierze pod uwagę, że Formularz może zawierać textarea i menu select. O wiele lepiej jest użyć metody serialize (), a następnie manipulować nią tak, jak trzeba. Dane z serialize () mogą być używane w Ajax post lub get, więc nie ma tam żadnego problemu.

 0
Author: Billy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-15 17:56:03

Mam nadzieję, że to komuś pomoże. :)

// 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: "[email protected]"
//   1: "[email protected]"
// 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;
};
 0
Author: Julian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-08 07:03:30

Wszystkie odpowiedzi są dobre, ale jeśli jest pole, które chcesz zignorować w tej funkcji? Łatwo, nadaj polu właściwość, na przykład ignore_this:

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

I w funkcji Serialize:

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

W ten sposób ignoruje się niektóre pola.

 0
Author: Marcelo Rocha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-16 19:17:35

Spróbuj użyć następującego kodu:

jQuery("#form").serializeArray().filter(obje => 
obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")
 0
Author: Teodor Rautu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-17 14:26:27

Dla wielu wybranych elementów (<select multiple="multiple">) zmodyfikowałem rozwiązanie z @ Jason Norwood-Young, aby działało.

Odpowiedź (jak napisano) pobiera tylko wartość z pierwszego elementu, który został wybrany, a nie wszystkie. Nie zainicjalizował ani nie zwrócił data, ten pierwszy wyrzucił błąd JavaScript.

Oto nowa wersja:

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
}

Użycie:

_get_values($('#form'))

UWAGA: Musisz tylko upewnić się, że name twojego select ma [] dołączone na jego końcu, na przykład:

<select name="favorite_colors[]" multiple="multiple">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>
 0
Author: tzazo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-21 16:37:12
$("#form-id").submit(function (e) { 
  e.preventDefault();
  inputs={};
  input_serialized =  $(this).serializeArray();
  input_serialized.forEach(field => {
    inputs[field.name] = field.value;
  })
  console.log(inputs)
});
 0
Author: Raushan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-18 22:10:20