0

text input have names with arrays styles (name="post[2][id]"). I need get this values in jQuery script with this structure names. So that I can work as a normal array.

$(document).ready(function(){   
    var data = {};
    data['post'] = {};

    var fields = $("#user input");

    $.each(fields, function(index, field) {
        data[$(field).attr('name')] = $(field).val();
    });

    console.log(data);
});


<div id="user">
    <input type="text" name="name" value="Joy" />
    <input type="text" name="post[1][id]" value="2" />
    <input type="text" name="post[1][name]" value="test" />
    <input type="text" name="post[2][id]" value="3" />
    <input type="text" name="post[2][name]" value="test 2" />
</div>

Now my name add like string in data variable, so this is very bad. I need this:

alert(data.post.1.id) // 2
1
  • Not sure what you're asking for help with... Commented Apr 24, 2013 at 17:27

1 Answer 1

2

Short answer:

Without extending jQuery's selector, you can make use of jQuery's contains selector: http://api.jquery.com/attribute-contains-selector/

Like this

$('input[name*="["][name*="]"]')

Translated it English, it means, give me the inputs where the name contains [ and ]


Long answer:

The short answer should pragmatically be adequate.

But FYI...

The duplicate use of [name...] is because of one downside, we cannot use wildcards in such selectors.

Another downside is they do not define strict order of occurrence. E.g. a name of post]1[ will also be matched.

If you really need to ensure the name has the correct string pattern, you can extend jQuery's selector to perform Regex operations for stricter selection rules.

Here's a good one: http://james.padolsey.com/javascript/regex-selector-for-jquery/

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.