删除字段后重置JavaScript计数器 [英] Reset JavaScript Counter after Deleting a field

查看:76
本文介绍了删除字段后重置JavaScript计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript函数,可使用计数器添加输入字段.现在,当我删除其中一个字段时,它将被删除,但计数器仍在继续! JS或JQuery中有什么方法可以重置计数器并自动递增计数器?

I have a javascript function that adds input fields with a counter. now, when i remove one of the fields it gets deleted but the counter continues! is there a way in JS or JQuery to reset the counter and auto increment the counter?

JS代码:

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value'+i+'" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').live('click', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();

                }
                return false;
        });
});

请检查 jsfiddle

说明: 我的字段是:

no. 1
no. 2
no. 3

我想要的是:删除#2之后:

what i want is: After deleting #2:

no. 1
no. 3
**To**:
no. 1
no. 2

谢谢

推荐答案

HTML

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
    <p>
        <label for="p_scnts"><input type="text" class="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
    </p>
</div>

Js

function resetIndexes(){
    var j = 1;   
    $('.p_scnt').each(function(){
        if( j > 1){
            $(this).attr('name', 'p_scnt_' + j);
            $(this).attr('placeholder', 'Input Value'+j);
        }   
        j++;    
    });
}


$(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents .p_scnt').size() + 1;

    $('#addScnt').on('click', function() {
        i = $('#p_scents .p_scnt').size() + 1;   
        $('<p><label for="p_scnts"><input type="text" size="20" class="p_scnt" name="p_scnt_' + i +'" value="" placeholder="Input Value'+i+'" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });

    $('#p_scents').on('click', '.remScnt', function() { 
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    resetIndexes();
            }
            return false;
    });
});

这是 JSFiddle

这篇关于删除字段后重置JavaScript计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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