views:

63

answers:

2

Newbie question. Given the following html.

<div id="mycontainer1" class="container">
<input type="text" class="name"/>
<input type="text" class="age"/>
</div>

<div id="mycontainer2" class="container">
<input type="text" class="name"/>
<input type="text" class="age"/>
</div>

I'm trying to create a function where I can pass an element id and an array that contains the classes of the input values I want to get.

So for example,

var inputClasses = ['name','age'];

getInputValue('.container', inputClasses);


     function getInputValue(elem, arr) {    
            $(elem).each(function() {
                // need a way to map items in array to variables

                // but how do I do this dynamically?
                var nameValue = $(this).find('.name').val();
                var ageValue = $(this).find('.age').val();

            });
+1  A: 

Try:

var inputClasses = ['name','age'];

console.log(getInputValues('#mycontainer1', inputClasses));

function getInputValues(elem, arr) {
  return $(elem).find("." + arr.join(",.")).map(function(val) {
    return $(this).val();
  }).get();
}
cletus
I think you want `find( '.' + arr.join(',.'))`.
tvanfosson
Might want to tag a `get()` on the end as well if a basic array instead of jQuery is desired as the output.
tvanfosson
@hanfosson good points (x2) :)
cletus
This is a great. If I understand correctly this gets single input value at a time. Is there a way to get multiple input values on each iteration?
BTW in my original post I meant to find elements by class NOT by id.should be getInputValue('.container', inputClasses);
A: 

Try this:

var inputClasses = ['name','age'];
var inputValues = getInputValue('#myContainer1', inputClasses);

 function getInputValue(elem, arr) {
     var out = [];

            for(i=0; i <= arr.length; i++) {
                var out[arr[i]] = $(elem+' .'+arr[i]).val();
            };

     return out;
}

You should now have an array inputValues that contains the values of every input field, with the class name as the index key.

For example, you could then read out the "name" value like this:

alert('Your name: '+inputValues['name']);
bobsoap