0

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();

            });
0

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think you want find( '.' + arr.join(',.')).
Might want to tag a get() on the end as well if a basic array instead of jQuery is desired as the output.
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);
1

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']);

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.