0

I have dynamic input fields inside the form. Data is being pulled from mysql table to populate each input field. I am using jquery to give the user the ability to add more input fields or to delete an input field. The delete button shows disabled and does not allow me to delete an entry. The delete is only to be disabled if there is less than two .clonedSection displaying inside the form. How can I fix this error? EXAMPLE

<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' />";

?>
8
  • This is a cool device, I'll take a look at it, but please get rid of all those annoying popus in the example. YOUR APP WORKS!?!?!? Commented Dec 1, 2013 at 19:19
  • @hanzo2001 Sorry about the ads. Its free hosting. Well the delete button is not working properly. Commented Dec 1, 2013 at 19:21
  • your example is functional on my browser. The delete button is awkwardly deactivated only on page load. When you add one person it becomes active and then it works as intended Commented Dec 1, 2013 at 19:22
  • @hanzo2001 Yes, that awkward deactivation is what I am trying to get rid of. Commented Dec 1, 2013 at 19:23
  • I'll take the liberty of rewriting part of your javascript/jQuery, I hope you don't mind Commented Dec 1, 2013 at 19:24

1 Answer 1

1

Ok, this is a quick solution

the last line of your javascript is

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

this means that this will be executed on page load, no matter the number of cloned sections. The solution would be either to

  • put it in an if clause and check the initial clonedSection Nodes
  • rewrite this mess and have it more clear

Your call. I'm currently rewriting the spaghetti you have there but if this suits you then I guess that's that.

Any questions, please ask

your javascript

this is not tested, it may not work but its intention is educational. Plus, half of all the code is to accomodate this strange way of formatting your 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);
});

Please write nice javascript, if you want to follow some good guidelines check out Crockford

Sign up to request clarification or add additional context in comments.

1 Comment

Alright will do so! Also could you post in your answer your rewrite. Thank you for your dedicated help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.