Obtain form input fields using jQuery?

2019-01-01 09:20发布

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?

22条回答
素衣白纱
2楼-- · 2019-01-01 09:59

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:

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

查看更多
爱死公子算了
3楼-- · 2019-01-01 10:00

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])
查看更多
时光乱了年华
4楼-- · 2019-01-01 10:03

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

});
查看更多
大哥的爱人
5楼-- · 2019-01-01 10:03

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;
});
查看更多
一个人的天荒地老
6楼-- · 2019-01-01 10:05

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

查看更多
刘海飞了
7楼-- · 2019-01-01 10:06

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+"']"); 
查看更多
登录 后发表回答