2

I know how to serialize the whole form like in example below or one specific field of the form by just changing the line:

data: $('form').serialize(), 

to

data: $('#input-field').serialize(), 

.

$(document).on('input paste', '#soap', function () { $.ajax({ type:'POST', url:'/soap', headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, data: $('form').serialize(), success:function(data){ $('input[id=msg]').val(data.msg); } }); }); 

But i want to serialize 2 input fields that have an id....how to do that?

1

2 Answers 2

5

Way 1: By comma separated selector you can serialize two fields together using following code

var seializedTwoFields = $('#input-field1,#input-field2').serialize(); 

Way 2: When you use the jQuery serialize() function, it simply turns your field into a string in the format a=1. So you can certainly apply this function to two fields and concatenate the result, with an & between them.

Please try this snippet.

var formfield1 = $('#input-field1').serialize(); var formfield2 = $('#input-field2').serialize(); var seializedTwoFields = formfield1+'&'+formfield2; 
4
  • hmm...i'm using Laravel so i just wanted to send the both input fields to my controller through ajax and get them with $var1 = $request->number and $var2 = $request->code. This works fine with data: $('form').serialize(),
    – lewis4u
    CommentedSep 23, 2016 at 10:59
  • this with coma , should be perfect...i'll try that now
    – lewis4u
    CommentedSep 23, 2016 at 11:01
  • @lewis4u check my updated answer I have shared two ways.CommentedSep 23, 2016 at 11:01
  • 1
    the one with coma is great! like this data: $('#number, #code').serialize(), i didn't know you can put a coma between two ids or fields
    – lewis4u
    CommentedSep 23, 2016 at 11:04
0

You can have a complete object from the serialized data like below:

var obj = {}; $('form').serializeArray().map(function (x) { obj[x.name] = x.value; }); 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.