Javascript 如何限制创建3以上的动态输入元素?
我的表单中有一个输入元素。当我单击加号时,它会创建动态输入字段。如何限制它,使其最多只生成3个输入字段,然后在屏幕上隐藏加号Javascript 如何限制创建3以上的动态输入元素?,javascript,jquery,html,dom,Javascript,Jquery,Html,Dom,我的表单中有一个输入元素。当我单击加号时,它会创建动态输入字段。如何限制它,使其最多只生成3个输入字段,然后在屏幕上隐藏加号 $(函数(){ $(文档).on('click','btn add',函数(e){ e、 预防默认值(); var controlForm=$('.controls-form:first'), currentEntry=$(this).parents('.entry:first'), newEntry=$(currentEntry.clone()).appendTo(c
$(函数(){
$(文档).on('click','btn add',函数(e){
e、 预防默认值();
var controlForm=$('.controls-form:first'),
currentEntry=$(this).parents('.entry:first'),
newEntry=$(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last).btn add')
.removeClass('btn-add')。addClass('btn-remove'))
.removeClass('btn-success').addClass('btn-danger'))
.html(“”);
}).on('click','btn remove',函数(e){
$(this).parents('.entry:first').remove();
e、 预防默认值();
返回false;
});
});代码>
我的HTML元素:
您可以检查表单中输入元素的计数
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
//this will check here if the number of input is less than 3
if($(".controls form input[type=text]").length < 3){
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
} else {
//Add your logic here for hiding the add button
}
});
$(文档).on('click','btn add',函数(e)
{
e、 预防默认值();
//如果输入的数量小于3,将在此处进行检查
if($(“.controls表单输入[type=text]”)。长度<3){
var controlForm=$('.controls-form:first'),
currentEntry=$(this).parents('.entry:first'),
newEntry=$(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last).btn add')
.removeClass('btn-add')。addClass('btn-remove'))
.removeClass('btn-success').addClass('btn-danger'))
.html(“”);
}否则{
//在此处添加隐藏“添加”按钮的逻辑
}
});
检查表单中的条目数,如果条目数超过2,请删除“添加”按钮:
$(函数(){
$(文档).on('click','btn add',函数(e){
e、 预防默认值();
var controlForm=$('.controls-form:first'),
currentEntry=$(this).parents('.entry:first'),
newEntry=$(currentEntry.clone()).appendTo(controlForm);
如果(计数=$('.controls表单>*')。长度>2){
newEntry.find('.btn add').remove();
}
newEntry.find('input').val('');
controlForm.find('.entry:not(:last).btn add')
.removeClass('btn-add')。addClass('btn-remove'))
.removeClass('btn-success').addClass('btn-danger'))
.html(“”);
}).on('click','btn remove',函数(e){
$(this).parents('.entry:first').remove();
e、 预防默认值();
返回false;
});
});代码>