可复制的输入验证不适用于不可复制的字段

时间:2013-01-18 13:58:27

标签: javascript jquery

我正在创建一个可复制的表单,但我遇到了一个小问题。

我有一个主要成员输入和一个可复制的依赖输入,它们通过id验证运行,根据你的id自动给你年龄和性别。

我的问题是,所有重复的内容都基于id而获得独特的年龄和性别,但主要成员获得了第一个依赖者的性别。

代码必须保持与现在相同的格式才能使用其余代码。

继承人jsFiddle:http://jsfiddle.net/dawidvdh/ZQwZm/ id的例子:85 0929 5266086 和代码:

jQuery的:

// JavaScript Document
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking

//Main Variables
var main_input_groups = ["main_group-1"];
var main_age_input_groups = ["main_age_group-1"];
var main_gender_input_groups = ["main_gender_group-1"];
//Main Variables
//General Variables
var input_groups = ["group-1"];
var age_input_groups = ["age-group-1"];
var gender_input_groups = ["gender-group-1"];
var idNumber;
var cell_values;
var pass_values;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var age_fields=[0,1];
var gender_fields=[0];
//Main Member generate
var main_id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var main_age_fields = [0,1];
var main_gender_fields = [0];
//Main Member generate
//Main Member inputs
var mainID;
var mainPAS;
var mainCon;
var mainCod;
//Main Member inputs
//Main Member gen
var main_id_input = "<input class='mainid' maxlength='1' name='mainid' type='text' />";
var main_age_input = "<input class='mainage' maxlength='1' name='mainage' type='text' />";
var main_gender_input = "<input class='maingender' maxlength='1 name='maingender' type='text' />";
//Main Member gen
var id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var age_input = "<input class='age' name='age' type='text' />";
var gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
//Generate variables
jQuery(document).ready(function(e) {
    //Member
    jQuery(main_id_fields).each(function() {
        jQuery(main_id_input).appendTo('#main_group-1');
    });
    jQuery(main_age_fields).each(function() {
        jQuery(main_age_input).appendTo('#main_age_group-1');
    });
    jQuery(main_gender_fields).each(function() {
        jQuery(main_gender_input).appendTo('#main_gender_group-1');
    });
    //Member
    //populate jquery generated fields
    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');
    });
    //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 gender_newDiv = 'gender-group-'+ g_counter;
        var age_newDiv = 'age-group-'+ g_counter;
        var id_newDiv = 'group-'+ g_counter;

        // Find div's inside the cloned object and set a new id's
        $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 );

        // You don't need to Loop thru the inputs to set the value
        $clonedDiv.find('input:checkbox').removeAttr('checked');
        $clonedDiv.find('input[type="text"]').val('');


        // Insert the cloned object 
        $clonedDiv.insertAfter("#dependant-" + oldId);
        age_input_groups.push(age_newDiv);
        gender_input_groups.push(gender_newDiv);
        input_groups.push(id_newDiv);
    }
    //Cloning Function
    //Validation
    function validate_Id(values) {
            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-group-'+g_counter;
                    var agevalues = $.map($('#'+id + ' input') , function(e,i){
                        $('#'+id + ' input').first().val(Math.floor(age / 10));
                        $('#'+id + ' input').last().val(age % 10);
                        //return $(e).val(age);
                    });
                });
               $.each(gender_input_groups , function(i){
                    var id = 'gender-group-'+g_counter;
                    var gendervalues = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(gender);
                    });
                });

                $.each(main_gender_input_groups , function(i){
                    var id = 'main_gender_group-'+g_counter;
                    var maingendervalues = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(gender);
                    });
                });

                $.each(main_age_input_groups , function(i){
                    var id = 'main_age_group-'+g_counter;
                    var mainagevalues = $.map($('#'+id + ' input') , function(e,i){
                        $('#'+id + ' input').first().val(Math.floor(age / 10));
                        $('#'+id + ' input').last().val(age % 10);
                    })
                });

                return idNumber;
            }
            else {
                console.log(idNumber + "-wrong");
            }
            return false;
        }

    function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
    //Validation
//Multiple Inputs function
//ID
    $(document).on('keydown', 'input.id', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
        }
    });

    $(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];
                    values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values);
                });
            }
        }
    });
//ID
//MainID
    $(document).on('keydown', 'input.mainid', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
        }
    });

    $(document).on('keyup', 'input.mainid', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.mainid').length) {
                $this.next().focus();
            } else {
                $.each(main_input_groups , function(i){
                    var id = main_input_groups[i];
                    values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values);
                });
            }
        }
    });
//MainID
//Multiple Inputs function

//Basic Validation
//Digits only
jQuery(".id").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
});
//Digits only
$('.error').hide();

//Basic Validation
//submit function
var result = {};
var dependants;
var mainmember;
var dep_counter = 0;
jQuery('#submit').click(function(){
    jQuery('.main-member').each(function(k, v){
        mainmember  = {}
        result['mainmember'] = [mainmember];
        mainmember['id'] = ''; 
        $(v).find('.mainid').each(function(){mainmember['id'] += $(this).val();});
        mainmember['age'] = ''; 
        $(v).find('.mainage').each(function(){
          mainmember['age'] += $(this).val(); 
        });
        mainmember['gender'] = $(v).find('.main_gender').val();
    });
    jQuery('.dependant').each(function(k, v){
        var dep_id = idNumber;
        var iden_values;
        dep_counter++
        dependants = {};
        result['dependant'+dep_counter] = [dependants];
        dependants['id'] = ''; 
        $(v).find('.id').each(function(){
          dependants['id'] += $(this).val(); 
        });
        dependants['age'] = ''; 
        $(v).find('.age').each(function(){
          dependants['age'] += $(this).val(); 
        });
        dependants['gender'] = $(v).find('.gender').val();
    });
    var jsonData = JSON.stringify(result);

    console.log(jsonData);

    jQuery.ajax({
        type: "POST",
        url: "mail.php",
        dataType: "json",
        data: {parameters: jsonData}
    });
});
//submit function
});

和HTML:

<div id="app_wrap">
    <div class="main-member">
        <div class="block_wrap left border_right">
            <div class="block">main id-number:<div id="main_group-1" class="right"></div></div>
            <div class="block_half left border_right">age:<div id="main_age_group-1" class="right"></div></div>
            <div class="block_half right">gender:<div id="main_gender_group-1" class="right"></div></div>
        </div>
    </div>

    <div id="dependant-1" class="dependant">
    <div id="dependant">
        <div class="block_wrap left border_right">
            <div class="block">duplicate id-number:<div id="group-1" class="right"></div></div>
            <div class="block_half left border_right">age:<div id="age-group-1" class="right"></div></div>
            <div class="block_half right">gender: <div id="gender-group-1" class="right"></div></div>
        </div>
    </div>
</div>
    <button id="clone">Add a Dependant</button>
    <button id="submit">submit</button>
</div>

如果需要进一步解释,请随时提出。 谢谢,非常感谢任何和所有的帮助。

1 个答案:

答案 0 :(得分:1)

以下是如何解决http://jsfiddle.net/mgechev/ZQwZm/12/

我对代码进行了大量简化,但你需要重构它以使其更具可读性。

这是JavaScript:

// JavaScript Document
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking

//Main Variables
var main_input_groups = ["group-1"];
var main_age_input_groups = ["age_group-1"];
var main_gender_input_groups = ["gender_group-1"];
//Main Variables
//General Variables
var input_groups = ["group-2"];
var age_input_groups = ["age-group-2"];
var gender_input_groups = ["gender-group-2"];
var idNumber;
var cell_values;
var pass_values;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var age_fields=[0,1];
var gender_fields=[0];
//Main Member generate
var main_id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var main_age_fields = [0,1];
var main_gender_fields = [0];
//Main Member generate
//Main Member inputs
var mainID;
var mainPAS;
var mainCon;
var mainCod;
//Main Member inputs
//Main Member gen
var main_id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var main_age_input = "<input class='age' name='age' type='text' />";
var main_gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
//Generate variables
jQuery(document).ready(function(e) {
    //Member
    jQuery(main_id_fields).each(function() {
        jQuery(main_id_input).appendTo('#group-1');
    });
    jQuery(main_age_fields).each(function() {
        jQuery(main_age_input).appendTo('#age_group-1');
    });
    jQuery(main_gender_fields).each(function() {
        jQuery(main_gender_input).appendTo('#gender_group-1');
    });
    //Member
    //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', currentdep);
        var gender_newDiv = 'gender-group-'+ g_counter;
        var age_newDiv = 'age-group-'+ g_counter;
        var id_newDiv = 'group-'+ g_counter;

        // Find div's inside the cloned object and set a new id's
        $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 );

        // You don't need to Loop thru the inputs to set the value
        $clonedDiv.find('input:checkbox').removeAttr('checked');
        $clonedDiv.find('input[type="text"]').val('');


        // Insert the cloned object 
        $clonedDiv.insertAfter("#dependant-" + oldId);
        age_input_groups.push(age_newDiv);
        gender_input_groups.push(gender_newDiv);
        input_groups.push(id_newDiv);
    }
    //Cloning Function
    //Validation
    function validate_Id(values, p) {
            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) {
                var aig = p.find('.age');
                aig.first().val(Math.floor(age / 10));
                aig.last().val(age % 10);
                p.find('.gender').val(gender);
                /*
                $.each(main_gender_input_groups , function(i){
                    var id = 'main_gender_group-'+g_counter;
                    var maingendervalues = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(gender);
                    });
                });

                $.each(main_age_input_groups , function(i){
                    var id = 'main_age_group-'+g_counter;
                    var mainagevalues = $.map($('#'+id + ' input') , function(e,i){
                        $('#'+id + ' input').first().val(Math.floor(age / 10));
                        $('#'+id + ' input').last().val(age % 10);
                    })
                });*/

                return idNumber;
            }
            else {
                console.log(idNumber + "-wrong");
            }
            return false;
        }
        clone_dependant();
    function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
    //Validation
//Multiple Inputs function
//ID
    $(document).on('keydown', 'input.id', function(e) {
        if (e.keyCode == 8) {
            $(this).val('');
            $(this).prev().val('');
            $(this).prev().focus();
        }
    });

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

    $(document).on('keyup', 'input.id', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.id').length) {
                $this.next().focus();
            } else {
                var main_input_groups = $this.parent();
                $.each(main_input_groups , function(i, el){
                    values = $.map($(el).children('input'), function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values, main_input_groups.parent().parent().parent());
                });
            }
        }
    });
//MainID
//Multiple Inputs function

//Basic Validation
//Digits only
jQuery(".id").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
});
//Digits only
$('.error').hide();

//Basic Validation
//submit function
var result = {};
var dependants;
var mainmember;
var dep_counter = 0;
jQuery('#submit').click(function(){
    jQuery('div[class*="dependant"]').each(function(k, v){
        var dep_id = idNumber;
        var iden_values;
        dep_counter++
        dependants = {};
        result['dependant'+k] = [dependants];
        dependants['id'] = ''; 
        $(v).find('.id').each(function(){
          dependants['id'] += $(this).val(); 
        });
        dependants['age'] = ''; 
        $(v).find('.age').each(function(){
          dependants['age'] += $(this).val(); 
        });
        dependants['gender'] = $(v).find('.gender').val();
    });
    var jsonData = JSON.stringify(result);

    console.log(jsonData);

    jQuery.ajax({
        type: "POST",
        url: "mail.php",
        dataType: "json",
        data: {parameters: jsonData}
    });
});
//submit function
});