jQuery的可克隆输入foreach覆盖值 [英] Jquery clone-able inputs foreach overwrites values

查看:63
本文介绍了jQuery的可克隆输入foreach覆盖值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在创建一个可克隆的id输入字段.

I'm currently creating a clone-able id input field..

唯一的问题是在验证ID之后提交,它在控制台中为所有重复项显示相同的值.

the only problem is on submit after validating the id it displays the same values for all duplicates in the console.

我想要实现的只是克隆字段,使其通过验证运行,并在提交时返回JSON中每个克隆字段的值.

what I'm trying to achieve is simply to clone the field make it run through the validation and on submit return the values for each cloned field in JSON.

任何帮助我们都感激不尽.

Any Help greatly appreciated.

Js Fiddle: http://jsfiddle.net/dawidvdh/tBYSA/4/

Js Fiddle: http://jsfiddle.net/dawidvdh/tBYSA/4/

然后是代码:

jQuery-

//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var input_groups = ["group-1"];
var idNumber;
var values;
//General Variables
//Generate variables
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var id_input = "<input class='id' maxlength='1' name='id' type='text' />";

jQuery(document).ready(function(e) {
    jQuery(id_fields).each(function() {
        jQuery(id_input).appendTo('#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 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 );

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


        // Insert the cloned object 
        $clonedDiv.insertAfter("#dependant-" + oldId);
        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){
                        return $(e).val(age);
                    });
                });
               $.each(gender_input_groups , function(i){
                    var id = 'gender-group-'+g_counter;
                    console.log(gender_input_groups);
                    var gendervalues = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val(gender);
                    });
                });
                return idNumber;
            }
            else {
                console.log(idNumber + "-wrong");
            }
            return false;
        }

    function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
//Validation
//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 {
                $.each(input_groups , function(i){
                    var id = input_groups[i];
                    values = $.map($('#'+id + ' input') , function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values);
                });
            }
        }
    });
//MainID
$(document).on("click", 'input[type="checkbox"]', function() {
    jQuery(this).siblings(":checked").removeAttr('checked');
});
//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(); 
            }   
        }
});
//Basic Validation
//submit function
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function(){
    jQuery('.dependant').each(function(k, v){
        dep_counter++
        dependants = {};
        result['dependant'+dep_counter] = [dependants];
        dependants['id'] = idNumber;
    });
    var jsonData = JSON.stringify(result);
    console.log(jsonData);
});
//submit function
});

,然后是HTML:

<div id="dependant-1" class="dependant">
    <div id="label">id-number:</div>            <div id="group-1"></div>
    <div id="error_id" class="error"></div>
</div>

<button id="clone">Add a Dependant</button>
<button id="submit">submit</button>

先谢谢您了:).

推荐答案

在函数validate_Id中,您使用的是全局变量idNumber,该变量将由参数values分配.因此,最终,该全局变量将成为最后一个经过验证的数字.

In function validate_Id, you're using a global variable idNumber, which will be assigned by argument values. So eventually this global variable will be the last validated number.

要解决此问题,可以将idNumber更改为由相应的dep_counter索引的数组.

To solve that, you could change idNumber to an array indexed by corresponding dep_counter.

例如,三个更改就足够了:

For example, 3 changes should be enough:

  1. var idNumber;替换为var idNumbers = [];

validate_Id(values);更改为:

var idNumber = validate_Id(values);

if (idNumber) { idNumbers.push(idNumber); }

if (idNumber) { idNumbers.push(idNumber); }

dependants['id'] = idNumber;更改为dependants['id'] = idNumbers[dep_counter];

顺便说一句,您似乎喜欢全局变量,应尽可能避免使用全局变量.更糟糕的是,您声明了一些局部变量,它们的名称与全局变量的名称相同.

BTW, you seem to like global variables, which should be avoided when possible. Even worse, you declared some local variables with the same name of the global ones.

这篇关于jQuery的可克隆输入foreach覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆