0

I've got some dynamic form with inputs like

<input type="text" name="admins[0]['email']">
<input type="text" name="admins[1]['email']">
<input type="text" name="admins[2]['email']">

And so on. When I do .serializeArray(); on it, They are treated as separated, different names. I would like output to be

admins
|
-->0
|  \-->email => value
-->1
|  \-->email => value
-->2
   \-->email => value

So "admins" would be single array. Is it possible? (I'm sending data with ajax)

2
  • Take the output of serializeArray() and customize it to suit your needs Commented Nov 18, 2013 at 11:10
  • Yes really :) jsfiddle.net/66A8p Commented Nov 18, 2013 at 11:37

2 Answers 2

1

Simple approach

var serializedArray = {};
$( "input, textarea" ).each( function( i, el ){
  var $field = $( this )
    , rawName = $field.attr( "name" )
    , matches = rawName.match( /^(.+?)\[\d+\]\['(.+)'\]$/ )
    , key
    , subKey
    , value = $field.val()
    , subValue = {]}
    ;

  if( matches ){

    if( !( key in serializedArray ) ){
      serializedArray[key] = [];
    }

    subValue[subKey] = value;
    serializedArray[key].push(subValue);

  } else {
    serializedArray[rawName] = value;

  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the startsWith syntax of jQuery.

var admins = new Array();
$( "input[name^='admins']" ).each(function(i, val){
    // val ==> admins[0]['email']
    // $(this).val() ==> the value of the input
    admins[i][val.substring(val.indexOf("'"), val.length-2);]
});

Jquery startsWith selector.

Jquery each info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.