1

So, i found my solution on how to dynamically add form element using jQuery and i implement it, and it works so smoothly. By the way, i made a GIS web app to provide precise resident location and information of a place. And i stuck on how to manipulate the adding of resident's information together with its members to the database.

My initial code:

JS

 $(document).ready(function() {
 $('#addRow').click(function() {
 $('<div/>', {
   'class': 'extraPerson',
   html: GetHtml()
 }).hide().appendTo('#container').slideDown('slow');
 });

 $(document).on('click', "#removeRow", function() {
 var len = $('.extraPerson').length;
 if (len <= -1) {
   $('.extraPerson [name=firstname]').slideUp('slow');
   $('.extraPerson [name=lastname]').slideUp('slow');
   $('.extraPerson [name=gender]').slideUp('slow');
   $(this).fadeOut('slow');
 } else {
   $('.extraPerson [name=firstname' + (len - 1) + ']').slideUp('slow');
   $('.extraPerson [name=lastname' + (len - 1) + ']').slideUp('slow');
   $('.extraPerson [name=gender' + (len - 1) + ']').slideUp('slow');
   $(this).fadeOut('slow');
 }
 });
 });

 function GetHtml() {
 var len = $('.extraPerson').length;
 var $html = $('.extraPersonTemplate').clone();
 $html.find('[name=firstname]')[0].name = "firstname" + len;
 $html.find('[name=lastname]')[0].name = "lastname" + len;
 $html.find('[name=gender]')[0].name = "gender" + len;
 return $html.html();
 }

HTML

<div class="extraPersonTemplate">
  <div class="controls controls-row">
    <input class="span3" placeholder="First Name" type="text" name="firstname">
    <input class="span3" placeholder="Last Name" type="text" name="lastname">
    <select class="span2" name="gender">
        <option value="Male">Male</option>
        <option value="Female">Female</option>
    </select>
    <a href="#" id="removeRow"><i class="icon-plus-sign icon-white"></i> Remove Row </a>
    </div>
</div>
<div id="container"></div>
<a href="#" id="addRow"><i class="icon-plus-sign icon-white"></i> Add another     family member</a>

CSS

.extraPersonTemplate {
  display: none;
}

Now, how do i validate the members if a user forgot to enter a value of a member even he/she clicked the add row or one of its inputs are null in jQuery???

And if i submit the form, how to add those inputted members to my MySQL database?

Any help, suggestions and ideas would be heavenly appreciated.

JSFiddle to the code above^

0

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.