我使用此示例http://jsfiddle.net/aaki/hMJEy/1/动态地将输入字段添加到表单中,这就像魅力一样。
这是代码:
使用Javascript:
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
HTML:
<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<input type="text" name="stuff[]">
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
但是现在我想从数据库中获取数据并将值放入表单中。这样数据就可以更新,然后再次保存在数据库中。
不幸的是,jQuery是我的弱点,并且现在已经挣扎了一段时间。有任何建议或工作实例吗?
非常感谢你。
答案 0 :(得分:3)
您需要将该数据转换为JSON字符串,然后使用 function addField( $wrapper ) {
var $elem = $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input');
$elem.val('').focus();
return $elem;
}
function loadData(){
$.getJSON( "http://www.json-generator.com/api/json/get/bSxiJZPXuG?indent=2", function(data) {
/*
[
{
"name": [
"Tom",
"Mike",
"Sam"
]
}
]
*/
for( var i = 0; i < data[0][ "name" ].length; i++ ) {
if ( i >= $('.multi-field input').length ) {
var $wrapper = $('.multi-fields'),
$elem = addField( $wrapper )
$elem.val( data[0][ "name" ][i] )
} else {
$('.multi-field input').eq(i).val( data[0][ "name" ][i] )
}
}
});
}
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
addField( $wrapper )
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
loadData();
方法加载JSON。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<input type="text" name="stuff[]">
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div><div id="images"></div>
</form>
$ sed -r ':a;N;s/^([^ ]*)( .*)\n\1(.*)$/\1\2 |\3/;ta;P;D' infile
TRINITY_GG_428_c0_g1_i1_orf1 PF13499.1 EF_hand_5 | PF00036.27 efhand | PF13405.1 EF_hand_4 | PF13833.1 EF_hand_6 | PF13202.1 EF_hand_3
TRINITY_GG_429_c0_g1_i1_orf1 PF00156.22 Pribosyltran
TRINITY_GG_431_c5_g1_i1_orf1 PF00475.13 IGPD
TRINITY_GG_461_c0_g1_i1_orf1 PF01208.12 URO-D | PF12876.2 Cellulase-like