Reputation: 1228
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();
});
Upvotes: 0
Views: 2669
Reputation: 625087
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();
}
Upvotes: 2
Reputation: 5104
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']);
Upvotes: 1