【发布时间】:2017-05-05 15:27:23
【问题描述】:
我正在使用 bootstrap/jquery 将带有动态字段的行(在运行时)添加到表单(除了静态字段)。我通过 formvalidation.io 得到了一些想法。第一行是静态的,但其余行是动态的。我为引导程序中的动态行创建了一个模板(但隐藏)。当用户点击“+”符号时,它使隐藏的模板(行)可见。
对于添加的每一行字段,我将 host_index 从 0 递增,这是该行中每个字段的 name 和 id 属性的一部分。每当我连续添加一个字段时,我都会立即为该字段添加验证器。我动态创建每个字段的名称和 id 参数。
动态字段(来自第二行)也需要通过远程调用进行验证。出于某种原因,当我尝试在远程调用中获取选择框或输入框(动态创建)的值时,我没有得到任何值。但是我在静态字段上得到了一个值。该控件根本不会转到第二行进行验证。不知道我错过了什么。
你能帮忙吗?
代码如下:
$(document).ready(function() {
var host_index = 0;
var val = Math.random();
$('#host_type')
// Add button click handler
.on('click', '.addButton', function() {
if(host_Index < 10){
host_index++;
var $template = $('#type_Template'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('dns-index', host_index)
.insertBefore($template);
// Update the name and id attributes
$clone
.find('[name="cat"]').attr('name', 'host_' + host_index + '_cat').end()
.find('[name="cat"]').attr('id', 'host_' + host_ndex + '_cat').end()
.find('[name="host"]').attr('name', 'host_' + host_ndex + '_host').end()
.find('[name="host"]').attr('id', 'host_' + host_ndex + '_host').end()
.find('[name="subnet"]').attr('name', 'host_' + host_ndex + '_subnet').end()
.find('[name="subnet"]').attr('id', 'host_' + host_ndex + '_subnet').end();
//Not going to this part
$clone.find('select[name="host_" + host_index + "_cat"]').rules('add', {
required: true
});
$clone.find('input[name="host_" + host_index + "_host"]').rules('add', {
required: true,
validate_host: true,
remote: {
url: '/host/data.cgi',
type: 'GET',
data: {
'mode': 'validate_host',
'location': function(){
return $("#location option:selected").text();
},
'category': function(){
//Not getting any value
var cat_id=$('select[name=host_'+host_index+'_cat option:selected]');
return cat_id.text();
},
'hostname': function() {
//Not getting any value
var host_id=$('input[name=host_'+host_index+'_host]');
return host_id.val();
},
'subnet': function() {
return $(subnet_id).val();
},
'val': val
},
dataFilter: function(data, type){
var json = JSON.parse(data);
...
...
return true;
}
}
});
}
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('dns-index');
// Remove element containing the fields
$row.remove();
});
$("#hostForm").validate({
//validate the first row and other static fields (with the remote call)
});
});
【问题讨论】:
标签: javascript jquery ajax twitter-bootstrap