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.