使用jquery添加/删除具有动态值的输入字段


Add/Delete input fields that have dynamic values with jquery

我在表单中有动态输入字段。从mysql表中提取数据来填充每个输入字段。我使用jquery为用户提供添加更多输入字段或删除输入字段的能力。delete按钮显示为已禁用,不允许我删除条目。只有当表单中显示的.clonedSection少于两个时,才会禁用delete。如何修复此错误?示例

<script>
$(document).ready(function () {
    $('#btnAdd').click(function () {
        var num = $('.clonedSection').length;
        var newNum = new Number(num + 1);
        var newSection = $('#pq_entry_' + num).clone().attr('id', 'pq_entry_' + newNum);
        newSection.children(':first').children(':first').attr('id', 'person_fname_' + newNum).attr('name', 'person_fname_' + newNum).attr('placeholder', 'Person #' + newNum + ' First Name');
        newSection.children(':nth-child(2)').children(':first').attr('id', 'person_lname_' + newNum).attr('name', 'person_lname_' + newNum); 
        newSection.children(':nth-child(3)').children(':first').attr('id', 'person_email_' + newNum).attr('name', 'person_email_' + newNum); 
        newSection.children(':nth-child(4)').children(':first').attr('id', 'person_phone_' + newNum).attr('name', 'person_phone_' + newNum); 
        newSection.children(':nth-child(5)').children(':first').attr('id', 'person_fax_' + newNum).attr('name', 'person_fax_' + newNum); 
        newSection.children(':nth-child(6)').children(':first').attr('id', 'person_contact_' + newNum).attr('name', 'person_contact_' + newNum);  
        newSection.children(':nth-child(7)').children(':first').attr('id', 'person_instructor_' + newNum).attr('name', 'person_instructor_' + newNum);
        newSection.insertAfter('#pq_entry_' + num).last();
        $('#btnDel').prop('disabled', '');
        if (newNum == 5) $('#btnAdd').prop('disabled', 'disabled');
    });
    $('#btnDel').click(function () {
        var num = $('.clonedSection').length; // how many "duplicatable" input fields we currently have
        $('#pq_entry_' + num).remove(); // remove the last element
        // enable the "add" button
        $('#btnAdd').prop('disabled', '');
        // if only one element remains, disable the "remove" button
        if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');
    });
    $('#btnDel').prop('disabled', 'disabled');
});
//http://jsfiddle.net/34rYv/87/
</script>
</head>
<body>
<form action="" method="post">
 <?php
//Database connection
try {
    $db_con = new PDO($dsn, $user, $password);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
} 
//Populate the input fields with data from mysql table 
$db_select3  = $db_con->prepare("
SELECT     a.name, 
           a.academy_id,
           p.contact_role,
           p.instructor_role,
           p.first_name,
           p.last_name,
           p.person_email,
           p.person_phone,
           p.person_fax
    FROM academy a
    LEFT JOIN person p ON a.academy_id = p.academy_id
    WHERE a.academy_id = 15
");
if (!$db_select3) return false;
if (!$db_select3->execute()) return false;
    $results3 = $db_select3->fetchAll('PDO::FETCH_ASSOC);
    if (empty($results3)) return false;
    $result3 = '';
echo "<strong>Personel Information:</strong>";
$s = 1;
foreach ($results3 as $value3){ 
    echo "<ul id='"pq_entry_".$s."'" class='"clonedSection'">";
    echo "<li><input id='"person_fname_".$s."'" name='"person_fname_".$s."'" placeholder='"Person #1 - First Name'" type='"text'" value='" . $value3['first_name'] ."'/></li>";
    echo "<li><input id='"person_lname_".$s."'" name='"person_lname_".$s."'" placeholder='"Last Name'" type='"text'" value='" . $value3['last_name'] ."'/></li>";
    echo "<li><input id='"person_email_".$s."'" name='"person_email_".$s."'" placeholder='"Email'" type='"text'" value='" . $value3['person_email'] ."'/></li>";
    echo "<li><input id='"person_phone_".$s."'" name='"person_phone_".$s."'" placeholder='"Phone'" type='"text'" value='" . $value3['person_phone'] ."'/></li>";
    echo "<li><input id='"person_fax_".$s."'" name='"person_fax_".$s."'" placeholder='"Fax'" type='"text'" value='" . $value3['person_fax'] ."'/></li>";
    echo "</ul>";
$s++;   
}   
echo "<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='delete Delete' />";
?>

好的,这是一个快速的解决方案

javascript的最后一行是

$('#btnDel').prop('disabled', 'disabled');

这意味着无论克隆的节有多少,都将在页面加载时执行。解决方案是

  • 将其放入if子句中,并检查初始clonedSection Nodes
  • 重写这个烂摊子,让它更清楚

你的电话。我现在正在重写你那里的意大利面条,但如果这适合你,我想就是这样。

有任何问题,请咨询

您的javascript

这并没有经过检验,它可能不起作用,但它的意图是教育性的加上,所有代码的一半都是为了适应这种奇怪的格式化html 的方式

$(document).ready(function () {
  var
    uniqueNum = 0,
    maxNumOfSections = 5,
    fields = ['fname','lname','email','phone','fax','contact','instructor'],
    container = $('.clonedSection').parent(),
    btnDelete = $('#btnDel'),
    btnAppend = $('#btnAdd'),
    onAdd,
    onDelete,
    fnInputCreator,
    fnInputSet,
    fnList;
  // make formatted inputs
  fnInputCreator = function (name) {
    var extra = name === 'fname' ? 'placeholder="Person #'+uniqueNum+' First Name"' : '';
    return '<li><input type="text" id="'+name+'" name="'+name+'"'+extra+' /></li>';
  };
  // make a set of inputs
  fnInputSet = function () {
    var r = '';
    fields.forEach(function(v){r += fnInputCreator('person_'+v+'_'+uniqueNum);});
    return r;
  };
  // make the input container
  fnList = function () {
    return '<ul id="pq_entry_'+uniqueNum+'" class="clonedSection">'+fnInputSet()+'</ul>';
  };
  // onClick event
  onAdd = function () {
    container.append(fnList());
    uniqueNum++;
    btnDelete.prop('disabled',false);
    if (uniqueNum === maxNumOfSections) btnAppend.prop('disabled',true);
  };
  // onClick event
  onDelete = function () {
    container.last().remove();
    btnAppend.prop('disabled',false);
    uniqueNum--;
    if (uniqueNum === 1) btnDelete.prop('disabled',true);
  };
  // add listeners
  btnAppend.click(onAdd);
  btnDelete.click(onDelete);
  // disable if only one left
  if (container.children().length < 2) btnDelete.prop('disabled',true);
});

请编写好的javascript,如果你想遵循一些好的准则,请查看Crockford