【发布时间】:2014-12-08 19:55:38
【问题描述】:
我一直在试验以下代码,似乎一切都解决了,除了在表单验证失败后强制克隆的字段保持打开状态。例如,如果一个或多个克隆字段打开,有人没有填写必填字段并提交表单,则打开的克隆字段在表单刷新后消失。 有人对我如何在提交或刷新表单时强制打开的克隆字段保持打开状态有任何建议吗?
谢谢, 抢
<script>
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // the numeric ID of the new input field being added
newElem = $('#group' + num).clone().attr('id', 'group' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
// manipulate the name/id values of the input inside the new element
//newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newElem.find('.prod_num').attr('for', 'ID' + newNum + '_product_name');
newElem.find('.input_prod_num').attr('id', 'ID' + newNum + '_product_name').attr('name', 'ID' + newNum + '_product_name').val('');
newElem.find('.serial_num').attr('for', 'ID' + newNum + '_Serial_number');
newElem.find('.input_serial_num').attr('id', 'ID' + newNum + '_Serial_number').attr('name', 'ID' + newNum + '_Serial_number').val('');
newElem.find('.purch_date').attr('for', 'ID' + newNum + '_purchase_Date').attr('class', 'purch_date');
// newElem.find('.input_purch_date').attr('id', 'ID' + newNum + '_purchase_Date').attr('name', 'ID' + newNum + '_purchase_Date').val('');
newElem.find('.input_purch_date').attr('id', 'ID' + newNum + '_purchase_Date').attr('name', 'ID' + newNum + '_purchase_Date').attr('class', 'purch_date').val('');
$('.purch_date').datepicker('destroy');
// insert the new element after the last "duplicatable" input field
$('#group' + num).after(newElem);
$('#ID' + newNum + '_product_name').focus();
var i = 0;
$('.purch_date').each(function () {
$(this).attr("id",'date' + i).datepicker();
i++;
});
$('.purch_date').datepicker();
// enable the "remove" button
$('#btnDel').attr('disabled', false);
// Change '5' below to the max number of times the form can be duplicated
if (newNum == 9)
$('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
});
$('#btnDel').click(function () {
// confirmation
if (confirm("Are you sure you wish to remove this product? This cannot be undone."))
{
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#group' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "add section");});
}
return false;
// remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', false);
});
$('#btnDel').attr('disabled', true);
});
</script>
【问题讨论】:
-
未来参考代码 sn-ps 用于可运行代码,以便我们可以轻松运行示例。如果您显示的代码块不是完全可运行的 sn-p,它应该缩进 4 个空格,并且看起来像没有 sn-p 块的格式化代码。
标签: javascript jquery forms