1

大家好,我目前正忙于尝试将可复制的表单转换为 jsonstring,对于每个重复项,它需要添加到字符串中,例如提交时使用一个表单,它给了我 -{"dependant1":[{"name":"lllll"}]}但是当我添加另一个表单时它给了我 -{"dependant1":[{"name":"xxx"}],"dependant2":[{"name":"xxx"}]}所以基本上是最新的一个覆盖前一个。

无论如何 JS Fiddle 链接 - http://jsfiddle.net/dawidvdh/zWwEb/

我真的不擅长解释事情..所以请提出任何问题。

继承人的代码:

JS

//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var name_input_groups = ["name-group-1"];
var surname_input_groups = ["surname-group-1"];
var input_groups = ["group-1"];
var age_input_groups = ["age-group-1"];
var gender_input_groups = ["gender-group-1"];
var town_input_groups = ["town-group-1"];
var cell_input_groups = ["cell-group-1"];
var pass_input_groups = ["pass-group-1"];
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var name_fields=[0];
var surname_fields=[0];
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var passport_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var cell_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var age_fields=[0];
var gender_fields=[0];
var town_fields=[0];
var relation_fields=[0];

var name_input = "<input class='name' name='name' />";
var surname_input = "<input class='surname' name='surname' />";
var id_input = "<input class='id' maxlength='1' />";
var age_input = "<input class='age' />";
var gender_input = "<input class='gender' maxlength='1' />";
var town_input = "<input class='town' />";
var cell_input = "<input class='cell' maxlength='1' />";
var pass_input = "<input class='pass' maxlength='1' />";
var relation_input ="<input type='checkbox' class='spouse' />" + 
                    "<input type='checkbox' class='ownchild' />" +
                    "<input type='checkbox' class='adopted' />" +
                    "<input type='checkbox' class='stepchild' />" +
                    "<input type='checkbox' class='parent' />" +
                    "<input type='checkbox' class='inlaw' />" +
                    "<input type='checkbox' class='brother' />" +
                    "<input type='checkbox' class='other' />";
//Generate variables
jQuery(document).ready(function(e) {
    //populate jquery generated fields
    jQuery(surname_fields).each(function() {
        jQuery(surname_input).appendTo('#surname-group-1');
    });
    jQuery(name_fields).each(function() {
        jQuery(name_input).appendTo('#name-group-1');
    });
    jQuery(id_fields).each(function() {
        jQuery(id_input).appendTo('#group-1');
    });
    jQuery(age_fields).each(function() {
        jQuery(age_input).appendTo('#age-group-1');
    });
    jQuery(gender_fields).each(function() {
        jQuery(gender_input).appendTo('#gender-group-1');
    });
    jQuery(town_fields).each(function() {
        jQuery(town_input).appendTo('#town-group-1');
    });
    jQuery(cell_fields).each(function() {
        jQuery(cell_input).appendTo('#cell-group-1');
    });
    jQuery(passport_fields).each(function() {
        jQuery(pass_input).appendTo('#pass-group-1');
    });
    jQuery(relation_fields).each(function() {
        jQuery(relation_input).appendTo('#relation-group-1');
    });

    //populate jquery generated fields

    //Cloning Function
    jQuery('#clone').click(function() {
        clone_dependant();
    });

    function clone_dependant() {
        // Store the value of the previous Id to insert the cloned div..
        var oldId = g_counter;
        g_counter++;
        currentdep ='dependant-'+g_counter;
        // Clone the Dependant Div and set a new id
        var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
        var cell_newDiv = 'cell-group-'+ g_counter;
        var town_newDiv = 'town-group-'+ g_counter;
        var gender_newDiv = 'gender-group-'+ g_counter;
        var age_newDiv = 'age-group-'+ g_counter;
        var pass_newDiv = 'pass-group-'+ g_counter;
        var id_newDiv = 'group-'+ g_counter;
        var name_newDiv = 'name-group-'+ g_counter;
        var surname_newDiv = 'surname-group-'+ g_counter;
        var relation_newDiv = 'relation-group-'+ g_counter;

        // Find div's inside the cloned object and set a new id's
        $clonedDiv.find('name-group-1').attr('id',"name-group-" + g_counter );
        $clonedDiv.find('surname-group-1').attr('id',"surname-group-" + g_counter );
        $clonedDiv.find('group-1').attr('id',"group-" + g_counter );
        $clonedDiv.find('age-group-1').attr('id',"age-group-" + g_counter );
        $clonedDiv.find('gender-group-1').attr('id',"gender-group-" + g_counter );
        $clonedDiv.find('town-group-1').attr('id',"town-group-" + g_counter );
        $clonedDiv.find('cell-group-1').attr('id',"cell-group-" + g_counter );
        $clonedDiv.find('pass-group-1').attr('id',"pass-group-" + g_counter );
        $clonedDiv.find('relation-group-1').attr('id',"relation-group-" + g_counter );

        // You don't need to Loop thru the inputs to set the value
        $clonedDiv.find('input').val('');

        // Insert the cloned object 
        $clonedDiv.insertAfter("#dependant-" + oldId);

        name_input_groups.push(name_newDiv);
        surname_input_groups.push(surname_newDiv);
        cell_input_groups.push(cell_newDiv);
        age_input_groups.push(age_newDiv);
        gender_input_groups.push(gender_newDiv);
        town_input_groups.push(town_newDiv);
        pass_input_groups.push(pass_newDiv);
        relation_input_groups.push(relation_newDiv);
        input_groups.push(id_newDiv);
    };
    //Cloning Function
    //Validation


    function validate_gen() {};

    function validate_Id(values) {
            var idNumber = values;
            var correct = true;
            if (idNumber.length != 13 || !isNumber(idNumber)) {correct = false;}
            var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
            var today = new Date();
            var id_date = tempDate.getDate();
            var id_month = tempDate.getMonth();
            var id_year = tempDate.getFullYear();
            var currentYear = (new Date).getFullYear();
            var age = Math.floor((today-tempDate) / (365.25 * 24 * 60 * 60 * 1000));
            var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
            if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;}
            var genderCode = idNumber.substring(6, 10);
            var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
            var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
            var tempTotal = 0;
            var checkSum = 0;
            var multiplier = 1;
            for (var i = 0; i < 13; ++i) {tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
                if (tempTotal > 9) {tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));}
                checkSum = checkSum + tempTotal;
                multiplier = (multiplier % 2 == 0) ? 1 : 2;}
            if ((checkSum % 10) != 0) {correct = false;};
            if (correct) {
                 $.each(age_input_groups , function(i){
                    var id = age_input_groups[i];
                    var values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(age);
                    });
                });
               $.each(gender_input_groups , function(i){
                    var id = gender_input_groups[i];
                    var values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(gender);
                    });
                });
                console.log(idNumber);
            }
            else {
                console.log(idNumber + "-wrong");
            }
            return false;}

        function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};

    function validate_Pass(pass_values) {
        console.log("passport"+pass_values);
    };

    function validate_Email() {};

    function validate_Cell(cell_values) {
        if (cell_values != 10){
            console.log("Cell= "+cell_values);
        }else{
            console.log("bad");
        }
    };
    //Validation
//Multiple Inputs function
//ID
    $(document).on('keydown', 'input.id', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
            //Validate(current);
        }
    });

    $(document).on('keyup', 'input.id', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.id').length) {
                $this.next().focus();
            } else {
                $.each(input_groups , function(i){
                    var id = input_groups[i];
                    var values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values);
                });
            }
        }
    });
//ID
//CELL
    $(document).on('keydown', 'input.cell', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
            //Validate(current);
        }
    });

    $(document).on('keyup', 'input.cell', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.cell').length) {
                $this.next().focus();
            } else {
                $.each(cell_input_groups , function(i){
                    var id = cell_input_groups[i];
                    var cell_values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Cell(cell_values);
                });
            }
        }
    });
//CELL
//Pasport
    //Multiple Inputs function
        $(document).on('keydown', 'input.pass', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
            //Validate(current);
        }
    });

    $(document).on('keyup', 'input.pass', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.pass').length) {
                $this.next().focus();
            } else {
                $.each(pass_input_groups , function(i){
                    var id = pass_input_groups[i];
                    var pass_values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Pass(pass_values);
                });
            }
        }
    });
//Pasport
//Multiple Inputs function
//submit function

var result = {};
var dependants = {};

jQuery('#submit').click(function(){

    $('.dependant').each(function(k, v){
        dependants['name'] = $(v).find('.name').val();
        result['dependant'+g_counter] = [dependants];
    });

    var jsonData = JSON.stringify(result);
    console.log(g_counter);
    console.log(jsonData);
});

//submit function
});

HTML

<div id="dependant-1" class="dependant">
    name<div id="name-group-1"></div>
    surname<div id="surname-group-1"></div>
    id<div id="group-1"></div>
    age<div id="age-group-1"></div>
    gender<div id="gender-group-1"></div>
    townofbirth<div id="town-group-1"></div>
    cell<div id="cell-group-1"></div>
    passport<div id="pass-group-1"></div>
    relationship<div id="relation-group-1"></div>
</div>

<button id="clone">clone</button>
<button id="submit">submit</button>
4

1 回答 1

3

很久以前,这个问题占用了我一半的工作日......

修复非常简单 - 移动以下行:

var 依赖 = {};

在里面

$('.dependant').each(function(...));

像这样:

$('.dependant').each(function(k, v){
    var dependants = {};
    dependants['name'] = $(v).find('.name').val();
    result['dependant'+g_counter] = [dependants];
});

这导致了您的问题,因为变量依赖项对于您的函数是全局的。您正在为其设置不同的值,然后 result[key] 指向它。因此,最后,在您的结果对象中,您有几个指向同一个变量的键。而且因为依赖项对于函数来说是全局的,所以它毕竟拥有最后一个值。

最后,结果对象的每个键都指向相同的值。

我希望这有帮助。

于 2013-01-15T07:04:25.360 回答