开发者

jQuery - dynamic variables?

Newbie question. Given the following html.

<d开发者_StackOverflowiv 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();

            });


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜