简体   繁体   中英

Adding new row to the table using javascript / jquery

I want to add row to the table on clicking Add button and delete row using Delete button using javascript/jquery. I have tried writing the following code:

<script src="/js/jquery-2.0.3.js"></script>
  <script>
    /* Javascript for phone numbers*/
    $(document).ready(function()
    { 
      var counter = 2;
      var count= 4;

      $("#add_phone").click(function() 
      {
        alert("whoah it worked");
        if(counter>=count)
        {
          alert("Only " + count + " Phone number allowed.");
          return false;
        }   

        var htmlToAppend = '<tr id="pn'+ counter +'"><th>
              <select class="phone_no">
                <option value="home">home</option>
                <option value="Business">Business</option>
                <option value="Business2">Business 2</option>
              </select>
            </th>
            <td><input type="text"/></td></tr>';
            $("#phone_number").append ( htmlToAppend );

        newTableRow.appendTo("#phone_number");
        counter++;
      });

      $("#delete_phone").click(function() 
      {
        if(counter==2)
        {
          alert("Cannot remove phone number");
          return false;
        }   
        counter--;

        $("#pn" + counter-1).remove();

      });
    });

But the alert message alert("whoah it worked"); doesn't get displayed ie its not entering the function.

<div class="info_type">
        Phone numbers  <hr>
        <table id="phone_number">
          <tr id="pn1">
            <th>
              <select class="phone_no">
                <option value="home">home</option>
                <option value="Business">Business</option>
                <option value="Business2">Business 2</option>
              </select>
            </th>
            <td><input type="text"/></td>
          </tr>  
        </table>
        <input type="button" id="add_phone" value="Add"/>
        <input type="button" id="delete_phone" value="Delete"/>  
      </div>

I really want this solution. Can anybody help me??

PS: I am using Ruby on rails

Your string append is not well formed.

 var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"> <option value="home">home</option> <option value="Business">Business</option> <option value="Business2">Business 2</option></select> </th><td><input type="text"/></td></tr>';

Working sample in fiddle http://jsfiddle.net/shree/jNA4x/

try to rewrite htmlToAppend variable with a \\n\\ in the end of each line

demo

You can't have line breaks in your htmlToAppend variable,

var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"><option value="home">home</option><option value="Business">Business</option><option value="Business2">Business 2</option></select></th><td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );

Example Code

A common pitfall for me as well.

increment the counter you did not increments it.

for more help use like the below example.

<html> 
    <h1>Add remove dynamically</h1>      
     <head>
     <title></title> 
     </head>     
 <body>

Living in:
<table id="purchaseItems" name="purchaseItems" style="display: inline-table;">
    <tr id="tr_1">
        <td>
            <input type="text" name="living_1" class="tbDescription next" required />
        </td>
        <td>
            <input type="text" name="biggest_1" class="next" required />
        </td>
        <td>
            <input type="text" name="nextbiggest_1" class="nextRow" required />
        </td>

        <td>
            <input type="button" name="addRow[]" id="remove_1" class="removeRow" value='-' />
        </td>

        <td>
            <input type="button" name="addRow[]" id="add_1" class="add" value='+' />
        </td>

    </tr>
</table>

</body>  
</html>
<script type="text/javascript">
$("#remove_1").hide();
$(document).ready(function () {

    $(document).on('click', '#purchaseItems .add', function () {

        var total_row = $('#purchaseItems tr').length;
        var rows = $('#purchaseItems tr').length+1;
      if(total_row < 5)
      {
        // clear the values
      $('#purchaseItems tr:last').after('<tr id="tr_'+rows+'"><td><input type="text" name="living_'+rows+'" id="living_'+rows+'" class="tbDescription next"></td><td><input type="text" name="biggest_'+rows+'" id="biggest_'+rows+'" class="next"></td><td><input type="text" name="nextbiggest_'+rows+'" id="nextbiggest_'+rows+'" class="nextRow"></td><td><input type="button" name="addRow[]" id="remove_'+rows+'" class="removeRow" value="-"></td><td><input type="button" name="addRow[]" id="add_'+rows+'" class="add" value="+"></td></tr>');
      $(".add").hide();
      $(".removeRow").show();
      $("#add_"+rows).show();
      }
      else
      {
        alert("Maximum limit reached.")
      }

    });

    $(document).on('keypress', '#purchaseItems .next', function (e) {
        if (e.which == 13) {
            var v = $(this).index('input:text');
            var n = v + 1;
            $('input:text').eq(n).focus();
            //$(this).next().focus();
        }
    });
    $(document).on('keypress', '#purchaseItems .nextRow', function (e) {
        if (e.which == 13) {
            $(this).closest('tr').find('.add').trigger('click');
            $(this).closest('tr').next().find('input:first').focus();
        }
    });
    $(document).on('click', '#purchaseItems .removeRow', function () {
        var total_row = $('#purchaseItems tr').length;
        if ($('#purchaseItems .add').length > 1) {
            $(this).closest('tr').remove();
            var last_tr_id = $('#purchaseItems tr:last').attr("id").split("_")[1];
            $("#add_"+last_tr_id).show();
        }
        if ($('#purchaseItems .add').length == 1) {
         $(".removeRow").hide();
        }
    });

});
</script>

Try this way using Jquery

<form id="myForm">

    <div class="clonedInput">
        <input type="text" class="phone_oa" id="textPhone1" name="input1" placeholder="Enter phone number" style="width: 110px;" />
        <input type="button" name="btnDelete1" class="btnDel" value="Remove" disabled="disabled" />
    </div>

    <div id="addDelButtons" style="margin-top: 10px;">
        <button type="button" id="btnAdd" class="btn" >Add Another Number</button>
    </div>  

</form>

Script

var inputs = 1; 

    $('#btnAdd').click(function() {
        $('.btnDel:disabled').removeAttr('disabled');
        var c = $('.clonedInput:first').clone(true);
        c.children(':text').attr('name','input'+ (++inputs) ).val('');
        c.children(':text').attr('id','textPhone'+ (inputs) ).val('');
        c.children(':button').attr('name','btnDelete'+ (inputs) );
        $('.clonedInput:last').after(c);

        $('#btnAdd').attr('disabled',($('.clonedInput').length  > 4));
    });

    $('.btnDel').click(function() {
        if (confirm('Confirm delete?')) {
            --inputs;
            $(this).closest('.clonedInput').remove();
            $('.btnDel').attr('disabled',($('.clonedInput').length  < 2));
            $('#btnAdd:disabled').removeAttr('disabled');
            fixNames();
        }
    });

    function fixNames(){
        var i = inputs;
        while(i--) {
            $('input:text')[i].name = 'input'+ (i+1);
            $('input:button')[i].name = 'btnDelete'+ (i+1);
        }
    }

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM