Jquery Dynamic Form Control

Previously I have discussed about dynamic form control on the following page https://imron02.wordpress.com/2013/08/16/jquery-button-add-field-from-input/. From latest page, I’ve made form control with dynamic add field, delete add field and move input field to up or bottom. But what is the difference of this tutorial?

The difference of this tutorial is now I will try to explain one by one of the jquery code. And I also make dynamic numbering.

For more detail, the first we must create example html file. So create example html like this:

<html>
<head>
    <title>Dynamic Form</title>
    <script src='http://code.jquery.com/jquery-latest.min.js'></script>
</head>
<body>
<table id="field">
    <tr>
        <td>Alternatif 1</td>
        <td><input type="text" /></td>
    </tr>
</table>
<button type="button">Add Field</button>
<button type="button">Delete Field</button>
</body>
</html>

Example I use latest jquery (or for now is version 1.10.2). Then we must add jquery code after document ready:

<html>
<head>
    <title>Dynamic Form</title>
    <script src='http://code.jquery.com/jquery-latest.min.js'></script>
</head>
<body>
<table id="field">
    <tr>
        <td>Alternatif 1</td>
        <td><input type="text" /></td>
    </tr>
</table>
<button type="button">Add Field</button>
<button type="button">Delete Field</button>
<script type="text/javascript">
$( document ).ready(function() {
    
});
</script>
</body>
</html>

Ok first we must add template script in html code. Html script is used for template if we click button “add field”

<button type="button" id="addField">Add Field</button>
<button type="button">Delete Field</button>

<!-- Template script -->
<script id="template" type="text/template">
<tr>
    <td class="number">Alternatif</td>
    <td><input type="text" /></td>
</tr>
</script>

<!-- jquery script -->
<script type="text/javascript">
$( document ).ready(function() {
    $("#addField").click(function( event ) {
        $($("#template").html()).appendTo($("#field tbody")).show( "slow" );
        event.preventDefault();
    });
});
</script>

Explanations:

  1. Line 13. We add id=”addField”. For what that id?

    id addField it used for jquery trigger function, so if I click Add Field button, jquery will catch id of that button.

  2. Line 16. This script just template and doesn’t effect the document, because this template it used for jquery
  3. Line 26. This means the code will be executed this script if document is ready
  4. Line 27. Jquery catch trigger from button Add Field with id addField
  5. Line 28. Jquery get script template (catch from script id=”template”) and insert to (appendTo) table with id=”field” (<table id=”field”>) and insert to tbody from that table after <tr> tag
  6. Line 29. The event.preventDefault() method stops the default action of an element from happening. Like return false

So if we run this code (example.html) we will get result like this:

If we look, there is a shortage, which is supposed to alternatif 1, alternatif 2, and so on. So to create like that, we must add jquery code and change html file like this:

<td>Alternatif <span class='num'>1</span></td>
        <td><input type="text" /></td>
    </tr>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>

<script id="template" type="text/template">
<tr>
    <td class="number">Alternatif</td>
    <td><input type="text" /></td>
</tr>
</script>

<!-- jquery script -->
<script type="text/javascript">
$( document ).ready(function() {
    $("#addField").click(function( event ) {
        $($("#template").html()).appendTo($("#field tbody")).show( "slow" );
       if( $("td").hasClass("number") ) {
            var i = parseInt($(".num:last").text())+1;
            $( $("<span class='num'> "+ i +" </span>") ).appendTo($(".number")).closest("td").removeClass('number');
        }
        event.preventDefault();
    });
});
</script>

Explanations:

  1. Line 9. We add class num.
  2. Line 18. We add class number.
  3. Line 28. I create code to check if td has class number. See line 18.
  4. Line 29. So if td has class number, run code $(“.num:last”).text() to get last number from td, example 1. And then convert that value to integer, because before the last number is a string. And then + 1. So if we click add field, we can get alternatif 1, 2, 3 and so on.
  5. Line 30. I create code to add span html tag with value is variable from i (look at line 29) and add to td with class number, and after add I remove class number. Why I remove? Becase if is not, we can get result alternatif 2, alternatif 23, alternatif 234 and so on. And that is wrong.

And if we run that code, we can get result like this:

And how to create if we click button delete field? And again we must change code to be like this:

<button type="button" id="deleteField">Delete Field</button>
 
<script id="template" type="text/template">
<tr>
    <td class="number">Alternatif</td>
    <td><input type="text" /></td>
</tr>
</script>
 
<!-- jquery script -->
<script type="text/javascript">
$( document ).ready(function() {
    $("#addField").click(function( event ) {
        $($("#template").html()).appendTo($("#field tbody")).show( "slow" );
       if( $("td").hasClass("number") ) {
            var i = parseInt($(".num:last").text())+1;
            $( $("<span class='num'> "+ i +" </span>") ).appendTo($(".number")).closest("td").removeClass('number');
        }
        event.preventDefault();
    });

    $("#deleteField").click(function( event ) {
        var lengthRow = $("#field tbody tr").length;
        if( lengthRow > 1 )
            $("#field tbody tr:last").remove();
        event.preventDefault();
    });
    
});
</script>

Explanations:

  1. Line 14. I add id deleteField for jquery trigger.
  2. Line 35. That code is if we click button with id deleteField, then jquery run function to processing
  3. Line 36. I create variable lengthRow to check length from tr on the table with id field
  4. Line 37. If length of tr more than 1, so run code from line 38
  5. Line 38. Run function remove (remove()) and remove to the last of tr (tr:last)

Bonus

We can create row up and rowdown function. So change example.html to be like this:

        <td><input type="text" /></td>
        <td><a href="#" class="fieldUp">Row Up</a> | <a href="#" class="fieldDown">Row Down</a></td>
    </tr>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
 
<script id="template" type="text/template">
<tr>
    <td class="number">Alternatif</td>
    <td><input type="text" /></td>
    <td><a href="#" class="fieldUp">Row Up</a> | <a href="#" class="fieldDown">Row Down</a></td>
</tr>
</script>
 
<!-- jquery script -->
<script type="text/javascript">
$( document ).ready(function() {
    $("#addField").click(function( event ) {
        $($("#template").html()).appendTo($("#field tbody")).show( "slow" );
       if( $("td").hasClass("number") ) {
            var i = parseInt($(".num:last").text())+1;
            $( $("<span class='num'> "+ i +" </span>") ).appendTo($(".number")).closest("td").removeClass('number');
        }
        event.preventDefault();
    });
 
    $("#deleteField").click(function( event ) {
        var lengthRow = $("#field tbody tr").length;
        if( lengthRow > 1 )
            $("#field tbody tr:last").remove();
        event.preventDefault();
    });

    $(document).on("click", ".fieldUp, .fieldDown", function( event ) {
        var row = $( event.target ).closest('tr');
        if( $(this).is(".fieldUp") )
            row.insertBefore(row.prev());
        else
            row.insertAfter(row.next());
        event.preventDefault();
    });
     
});
</script>

Explanations:

  1. Line 11. I added new td with value is anchor tag with class fieldUp and fieldDown
  2. Line 21. Same with line 11, I add new td for fieldUp and fieldDown
  3. Line 44. So if document with class “fieldUp” or “fieldDown” and get trigger clicked, so run some function from jquery
  4. Line 45. I create variable to get this tr (tr is clicked/current tr) with function “closest”
  5. Line 46. If this tr with class “fieldUp” is clicked, so run code line 47.
  6. Line 47. Insert variabel row before (insertBefore) previous row (prev())
  7. Line 48, 49 If else Insert variabel row after (insertAfter) next row (next())

And if we run that code, we can get result like this if we click anchor field up or field down:

Full Source code

This is full source code:

<html>
<head>
    <title>Dynamic Form</title>
    <script src='http://code.jquery.com/jquery-latest.min.js'></script>
</head>
<body>
<table id="field">
    <tr>
        <td>Alternatif <span class='num'>1</span></td>
        <td><input type="text" /></td>
        <td><a href="#" class="fieldUp">Row Up</a> | <a href="#" class="fieldDown">Row Down</a></td>
    </tr>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>

<!-- Template script -->
<script id="template" type="text/template">
<tr>
    <td class="number">Alternatif</td>
    <td><input type="text" /></td>
     <td><a href="#" class="fieldUp">Row Up</a> | <a href="#" class="fieldDown">Row Down</a></td>
</tr>
</script>

<!-- jquery script -->
<script type="text/javascript">
$( document ).ready(function() {
    
    $("#addField").click(function( event ) {
        $($("#template").html()).appendTo($("#field tbody")).show( "slow" );
        if( $("td").hasClass("number") ) {
            var i = parseInt($(".num:last").text())+1;
            $( $("<span class='num'> "+ i +" </span>") ).appendTo($(".number")).closest("td").removeClass('number');
        }
        event.preventDefault();
    });
    
    $("#deleteField").click(function( event ) {
        var lengthRow = $("#field tbody tr").length;
        if( lengthRow > 1 )
            $("#field tbody tr:last").remove();
        event.preventDefault();
    });
    
    $(document).on("click", ".fieldUp, .fieldDown", function( event ) {
        var row = $( event.target ).closest('tr');
        if( $(this).is(".fieldUp") )
            row.insertBefore(row.prev());
        else
            row.insertAfter(row.next());
        event.preventDefault();
    });
    
});
</script>
</body>
</html>

Example online result

Look at this link: http://jsfiddle.net/imron02/FSGbh/1/ or full screen result http://jsfiddle.net/imron02/FSGbh/1/embedded/result/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s