0

In a previous question, I learned how to generate dynamic form elements with increasing element Ids.

Now, I'm having trouble figuring out a way to assign variables that equal the dynamically created form elements.

My form has six inputs with IDs as such:

box1_
box2_
box3_
box4_
box5_
box6_

Each clone of the form, adds an incrementing numeral to the end of the id, such that the first clone has boxes ending in 1, the second clone has boxes ending in 2, and such.

Here is my form cloning code, borrowed from the answer to my earlier question:

$(document).ready(function () {
    // show hidden inputs on POSITIVE selection
    $(document).on('change', '.zero_form select.first_input', function () {
        var sel = $(this).val();
        $(this).parent().find('.hide').toggle(sel == 'POSITIVE');
    });
    $(document).on('click', '.zero_form .removebutton', function () {
        $(this).closest("div").remove();
    });

    // clone fields  
    var form_index = 0;
    $("#add").click(function () {
        form_index++;
        $(this).parent().before($("#zero_form").clone().attr("id", "zero_form" + form_index));
        $("#zero_form" + form_index).css("display", "inline");
        $("#zero_form" + form_index + " :input").each(function () {
            $(this).attr("id", $(this).attr("id") + form_index);
        });
    });

});

I would like to dynamically create variables that capture the value of each element as it is created. For example, if I created two cloned fields, I would have inputs with the IDs:

box1_1, box2_1, box3_1, box4_1, box5_1, box6_1 &
box1_2, box2_2, box3_2, box4_2, box5_2, box6_2

I would want the variables as such:

var part1_1 = $('#box1_1').val();
var part2_1 = $('#box2_1').val();
...
var part1_6 = $('#box1_6').val();
var part2_6 = $('#box2_6').val(); etc..

This is what I've tried as an attempt to generate dynamic variables - I don't get any console errors, but I cannot verify that the variables exist and are accessible within my function?

script

function printOut() {
    var dxOut = 'Output\n';

    var part1_ = [];
    var part2_ = [];
    var part3_ = [];
    var part4_ = [];
    var part5_ = [];
    var part6_ = [];



// I'm not sure how to set the length of i to the # of inputs, so I chose 30 for now
    for (var i=1; i <= 30; i++){
    part1_[i] = $('#box1_'+i).val();
    part2_[i] = $('#box2_'+i).val();
    part3_[i] = $('#box3_'+i).val();
    part4_[i] = $('#box4_'+i).val();
    part5_[i] = $('#box5_'+i).val();
    part6_[i] = $('#box6_'+i).val();
    }

    return part1_;
    return part2_;
    return part3_;
    return part4_;
    return part5_;
    return part6_;

    dxOut += part1_1 +'\n'+part2_1+'\n'+part3_1;

        $('#output').val(dxOut);

  }

Here is a fiddle, in case it helps.

Thanks for the help.

Community
  • 1
  • 1
user1837608
  • 930
  • 2
  • 11
  • 37

2 Answers2

1

You have 3 ways to do this:

Create an array

The easiest way, and probably the preferred method if you have no particular reason to need explicit variables for each would be to use an array.

// Adding to array
var values = [];
$('#zero_form ' + form_index + ' input').each(function() {
   values.push($(this).val()));
});

// Outputting from array
values.forEach(function(value) {
   // do something with value
});

// Access just one
console.log(values[0]);

Create an object

This is very similar to the array method, though it allows you to name each item, if that is important later.

// Adding to object
var values = {};
$('#zero_form ' + form_index + ' input').each(function() {
   values[$(this).attr('name')] = ($(this).val()));
});

// Outputting from object
for (var name in values) {
   if (values.hasOwnProperty(name)) {
       var value = values[name];
       // do something with value
   }
});

// Access just one
console.log(values['item1']);
// or
console.log(values.item1);

Create dynamic variables

If you really need them to be individual variables, you can create and access them by treating window like an object.

In your particular case, I would NOT do things with this technique. I only include it to show how to create dynamically named variables.

// Adding to window/global
$('#zero_form ' + form_index + ' input').each(function() {
   window['input_' + $(this).attr('name')] = ($(this).val()));
});

// Outputting from window/global
for (var name in window) {
   if (/^input_/.test(name) && window.hasOwnProperty(name)) {
       var value = window[name];
       // do something with value
   }
});

// Access just one
console.log(window['item1']);
// or
console.log(item1);
samanime
  • 25,408
  • 15
  • 90
  • 139
  • Thanks for the nice explanations. This type of manipulation is a little more complex than I've been doing. I think your 2nd option may work - but can I use `values.hasOwnProperty(id)` instead of name? Also, is it possible to make unique variables equal to the input values? I'm not sure if that is already what your example intends to do. – user1837608 Feb 27 '14 at 00:02
  • Yes, you can use any identifier, like the ID. Also that is what the example does. `values[$(this).attr('name')] = ($(this).val())); });` sets the value of the input to a field that uses its name. To use the ID, just change `attr('name')` to `attr('id')`. – samanime Feb 27 '14 at 00:15
  • One more clarification, how do the variables generated get recalled individually? Meaning, if I only wanted, say, the variable whose value refers to the input with id=box2_2? – user1837608 Feb 27 '14 at 02:57
  • I updated my answer to include an example of accessing just one of each. Assumes that 'item1' was the name of the element. – samanime Feb 27 '14 at 17:47
0

1) Create an empty array

2) Loop through you element

3) fill the array as you go

emptyArray = [];

$("#zero_form" + form_index + " :input").each(function () {
  var inputValue = $(this).value;  
  emptyArray.push(inputValue);
});  
Frederic Nault
  • 986
  • 9
  • 14