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

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

本文介绍了可重复输入验证不适用于不可重复字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建可重复使用的表单,但是我遇到了一个小问题.

I'm in the process of creating a duplicate-able form, i have run into a slight problem though.

我有一个主要成员输入和一个可重复的从属输入,这些输入通过id验证运行,并根据您的id自动给您年龄和性别.

i have a main-member inputs and a duplicate-able dependent inputs that gets run through an id validation, that automatically gives you age and sex based on your id.

我的问题是,所有重复项都具有唯一的年龄和性别,但主要成员却获得了第一个受抚养者的性别.

and my problem is, all the duplicates get unique ages and sex's based on there id but the main member gets the sex of the first dependent.

该代码必须保持与现在的格式相同,才能与其余代码一起使用.

The code has to stay in the same format as it is now to work with the rest of the code.

这是一个jsFiddle: http://jsfiddle.net/dawidvdh/ZQwZm/id的示例:85 0929 5266086和代码:

heres a jsFiddle: http://jsfiddle.net/dawidvdh/ZQwZm/example of an id: 85 0929 5266086and the code:

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>

如果需要任何进一步的解释,请随时提出.谢谢,所有帮助都将不胜感激.

if any further explanation is needed feel free to ask.Thanks, any and all help is greatly appreciated.

推荐答案

这是如何解决的方法 http ://jsfiddle.net/mgechev/ZQwZm/12/

我对代码进行了很多简化,但是您需要对其进行重构以使其更具可读性.

I simplified the code a lot but you need to refactor it to became more readable.

这是JavaScript:

Here is the 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
});

这篇关于可重复输入验证不适用于不可重复字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:15