Kevin Whitaker
Kevin Whitaker

Reputation: 13425

Separate array of elements by attribute

Let's say I've got a form with several inputs, and I use a pretty standard jQuery statement to get them all:

var inputs = $("#some-form").find("input")

Now, I'd like to act on those inputs, but let's say I want to treat the radio button and/or checkbox groups as a single thing. How can I split inputs out into elements grouped by an attribute, say name. Note, that I don't know what the name is going to be when the processing starts.

In human terms, I need the logic do do something along the lines of:

Let me iterate over the list of inputs. For each input, let me check to see if it's already been added to a placeholder array. If so, leave it alone. If not, add it and everything with it's name to said placeholder array (as a sub array).

Essentially, I'd like something like this:

[[<input type="text" name="name1">], [<input type="radio" name="name2">,<input type="radio" name="name2">]]

Upvotes: 0

Views: 103

Answers (2)

Domenic
Domenic

Reputation: 112817

function getInputsPartitioned(formEl) {
    var inputEls = formEl.querySelectorAll("input");

    var inputsByName = Object.create(null);
    for (var i = 0; i < inputEls.length; ++i) {
        var inputEl = inputEls[i];
        var name = inputEl.name;

        if (!(name in inputsByName)) {
            inputsByName[name] = [];
        }
        inputsByName[name].push(inputEl);
    }

    // `inputsByName` now looks like this:
    // {
    //     name1: [<input type="text" name="name1">],
    //     name2: [<input type="radio" name="name2">, <input type="radio" name="name2">]
    // }

    // To get it into arrays:

    return Object.keys(inputsByName).map(function (name) {
        return inputsByName[name];
    });
}

Bonus: no jQuery needed.

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using attribute selector inside a filter.

var $formInput = $('#some-form').find('input');
var inputText = $formInput.filter('[type=text]')
var otherInput = $formInput.filter("[type=radio]")
                          .add($formInput.filter('[type=checkbox]'));

or even better

var otherInput = $formInput.filter(function () {
                     return this.type == 'radio' || this.type == 'checkbox';
                  });

DEMO: http://jsfiddle.net/utwaf/

How can I split inputs out into elements grouped by an attribute, say name

var elements = []; //elements by name
var $formInput = $('#some-form').find('input');
elements.push($formInput.filter(function() { 
   return this.name == 'name1';
});
elements.push($formInput.filter(function() { 
   return this.name == 'name2';
});

Note: All elements pushed into the array are jQuery objects.

Upvotes: 2

Related Questions