简体   繁体   English

生成等于动态创建的表单元素的变量

[英]Generate variables that equal dynamically created form elements

In a previous question , I learned how to generate dynamic form elements with increasing element Ids. 在上一个问题中 ,我学习了如何通过增加元素ID来生成动态表单元素。

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: 我的表单有六个输入,其ID分别为:

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. 形式的每个克隆都在id的末尾添加一个递增数字,以使第一个克隆的框以1结尾,第二个克隆的框以2结尾,依此类推。

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: 例如,如果我创建了两个克隆的字段,那么我将获得带有ID的输入:

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. 谢谢您的帮助。

You have 3 ways to do this: 您有3种方法可以做到这一点:

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. 这与array方法非常相似,但是如果以后很重要,它可以让您为每个项目命名。

// 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. 如果确实需要将它们作为单独的变量,则可以通过将window视为对象来创建和访问它们。

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

1) Create an empty array 1)创建一个空数组

2) Loop through you element 2)循环遍历您的元素

3) fill the array as you go 3)随手填充数组

emptyArray = [];

$("#zero_form" + form_index + " :input").each(function () {
  var inputValue = $(this).value;  
  emptyArray.push(inputValue);
});  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM