2

I am creating add and delete rows dynamically but it seems that my code is not working properly please help me. As i'm unable to get alert as i m trying to append table rows but before that it will check wheather table exist or not than add row

$(document).ready(function()
{
    $("#add_Row").click(function()
    {
        if($(".test").html() == null)
        {
            alert("empty");         
         $("#add_Row").click(function()
          {
              alert("I am here");
            $('.test').append(
            "<tr><td><input type="text"     class="index_txtBox"/></td>
                 <td><input type="checkbox" class="check_box"/></td> 
                 <td><input type="text"     class="txt_Box"/></td>
                 <td><select><option></option></select></td></tr>
            ");             
          });   

          $("#delete_Row").click(function()
          {
              if($(".test tr").length != 0)
              {               
                  $(".test tr:last-child").remove();
              }
              else
              {
                  alert("Now table is empty");
              }
          }
        }
    });     
});
</script>
</head>
<body>
<div class="buttons">
<input type="button"   id="add_Row"    value="Add Row" />
<input type="button"   id="delete_Row" value="Delete Row" />
<input type="checkbox" id="select_All" value="Select All" />Select All

</div>
5
  • there are multiple ` $("#add_Row").click(function() {` in the script... prepare a demo to replicate the issue Commented Mar 10, 2016 at 4:58
  • also the class test is missing in the code provided pls include all relevant code to the OP Commented Mar 10, 2016 at 4:59
  • also check how to use string literals with quotes within them Commented Mar 10, 2016 at 5:00
  • 1
    jsfiddle.net/arunpjohny/64o9hucL/2 Commented Mar 10, 2016 at 5:32
  • How do I delete particular row as my code delete all rows when i click on delete row button here is my code:$("#delete_Row").click(function() { if($("input[type=checkbox]").is(":checked")) { alert("I am in delete option"); $(".test tr").remove(); } Commented Mar 10, 2016 at 6:18

5 Answers 5

2

First of you are trying to append a invalid string. Your string should not have breaks between them (you can escape them using \), instead have your string within one line. And use single quotes to surround the entire string and double quotes around other HTML attributes or you can have it the other way around.

Something like this:

var text= "<tr><td><input type='text''     class='index_txtBox'/></td>"
                 +"<td><input type='checkbox' class='check_box'/></td>" 
                 +"<td><input type='text'     class='txt_Box'/></td>"
                 +"<td><select><option></option></select></td></tr>";

Now, for the add button:

$(document).on('click', '#add_row', function(){
  $('#test').append(text) //append the var defined
});

And then the delete button, delete the rows that are checked:

$(document).on('click', '#del_row', function(){
if(!$.trim($('#test').html()).length){ // If empty, do a  alert
  alert ("Now table is empty")
 }else{
   $('#test').children('tr').find('input[type=checkbox]:checked').each(function () { // look for the checked input
    $(this).closest('tr').remove(); // remove the entire row closest to it
    });
  }
});

Here is a Demo.

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

3 Comments

ok. But how do i delete that row which is checked not the last row of table
@Shanky You can use a loop to check if the item is checked and then remove them like here: jsfiddle.net/ns5efkpe/3
@Shanky, I think I deserve the best answer as my answer is the most accurate to check if the div has any value, and it also deletes the checked rows just as your requirements
2

This may work:

$(document).ready(function()
{
    $("#add_Row").on('click',function()
    {
        alert("I am here");
         $('.test').append('<tr><td><input type="text" class="index_txtBox"/></td><td><input type="checkbox" class="check_box"/></td><td><input type="text" class="txt_Box"/></td><td><select><option></option></select></td></tr>');             
        });
    $('#delete_Row').on('click',function()
    {
              if($(".test tr").length != 0)
              {               
                  $(".test tr:last-child").remove();
              }
              else
              {
                  alert("Now table is empty");
              }
   });    
});

You don't need to test if .test is empty because you are adding to it and append is work on empty elements too

4 Comments

are you sure the string literal "<tr><td><input type="text" class="index_txtBox"/></td> is correct
it is still showing error that is why i'm unable to run this. actully it is showing error in $('.test').append is this line
do you have a DOM object with the class of .test?
actully my intension is when i click add row it should check if first time table exist or not if not than create table after that add row otherwise add row
0

You have to correct following - 1. why to register multiple click event handler for add_row - remove one 2. Delete button click handler should be outside the add row click handler 3. Use of string literal is not proper while appending new row.

Please follow the below code

 $(document).ready(function()
    {
        //keep this add_row click handler only and remove other
        $("#add_Row").click(function()
        {
            //for alert if test is empty
            if($(".test").html() == null)
            {
                alert("empty");         
              } 
                  alert("I am here");
                //corrected string literal
                $('.test').append(
                '<tr><td><input type="text"     class="index_txtBox"/></td>
                     <td><input type="checkbox" class="check_box"/></td> 
                     <td><input type="text"     class="txt_Box"/></td>
                     <td><select><option></option></select></td></tr>
                ');

        });  

       //delete_row click handler outside add_row
        $("#delete_Row").click(function()
              {
                  if($(".test tr").length != 0)
                  {               
                      $(".test tr:last-child").remove();
                  }
                  else
                  {
                      alert("Now table is empty");
                  }
            });   
    });

Comments

0

if you want to add a new row on clicking add_row button and remove the last row on clicking delete_row, Please follow the below code:

html

<table class="test">
   <tbody></tbody>
</table>
<div class="buttons">
    <input type="button"   id="add_Row"    value="Add Row" />
    <input type="button"   id="delete_Row" value="Delete Row" />
    <input type="checkbox" id="select_All" value="Select All" />Select All
</div>

javascript

$(document).ready(function()
{
    var $target_area= $(".test").find('tbody');
    $("#add_Row").on("click", function(){
        var $new_row    = '<tr><td><input type="text" class="index_txtBox"/></td><td><input type="checkbox" class="check_box"/></td><td><input type="text" class="txt_Box"/></td><td><select><option></option></select></td></tr>';
        $target_area.append($new_row);
    });
    $("#delete_Row").on('click',function(){
        $target_area.find('tr:last').remove();
    });
});

Comments

0

To create dynamic Row and Column with ADD/Remove button

HTML

<table id="TblPassenger">
  <thead>
      <tr>
          <th><b>Sr.</b></th>
          <th><b>Name</b></th>
          <th><b>Age</b></th>
          <th><b>Gender</b></th>
          <th><b>Berth Preference</b></th>
          <th><input type="button" id="AddPass" title="Add new passenger" value="Add" /></th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><b>1</b></td>
          <td><input type="text" maxlength="16" placeholder="Name 1" data-case="Upper" id="name_0" class="Textbox_Mid" /> </td>
          <td><input type="text" title="Age" placeholder="Age" id="Age_0" maxlength="2" data-id="numerical" class="Textbox_TooShort" /></td>
          <td>
              <select id="Gender_0" title="Gender" class="ddl">
                  <option value="M">Male</option>
                  <option value="F">Female</option>
              </select>
          </td>
          <td>
              <select id="BP_0" title="Berth Preference" class="ddl">
                  <option value="  ">No Preference</option>
                  <option value="LB">LOWER</option>
                  <option value="MB">MIDDLE</option>
                  <option value="UB">UPPER</option>
                  <option value="SL">SIDE LOWER</option>
                  <option value="SU">SIDE UPPER</option>
              </select>
          </td>
          <td><input type="button" id="DeletePass_0" title="Delete this passenger" value="Del" /> </td>
      </tr>
  </tbody>
  <tfoot>
      <tr>
          <td colspan="4"><b>Mobile No.    </b><input type="text" id="txtMobileNo" data-msg="Mobile No. should be 10 digit" data-minlength="10" placeholder="Mobile No." title="Enter mobile No. to get SMS" maxlength="10" data-id="numerical" class="Textbox_Mid" /></td>
          <td colspan="2"></td>
      </tr>
  </tfoot>
</table>

Jquery

function AddPassenger() {
    var btnIndex = $('input[id*="DeletePass_"]').length;
    if (btnIndex < 4) {
        var Sr = btnIndex + 1;
        $('#TblPassenger').find('tbody').append('<tr>'
                               + '<td>' + Sr + '</td>'
                               + '<td><input type="text" data-case="Upper" maxlength="16" placeholder="Name ' + Sr + '" id="name_' + btnIndex + '" class="Textbox_Mid" /> </td>'
                               + '<td><input type="text" title="Age" placeholder="Age" id="Age_' + btnIndex + '" data-id="numerical" maxlength="2" class="Textbox_TooShort" /></td>'
                               + '<td><select id="Gender_' + btnIndex + '" title="Gender" class="ddl"><option value="M">Male</option><option value="F">Female</option></select></td>'
                               + '<td><select id="BP_' + btnIndex + '" title="Beath Preference" class="ddl"><option value="  ">No Preference</option><option value="LB">LOWER</option><option value="MB">MIDDLE</option><option value="UB">UPPER</option><option value="SL">SIDE LOWER</option><option value="SU">SIDE UPPER</option></select></td>'
                               + '<td><input type="button" title="Delete this passenger" id="DeletePass_' + btnIndex + '" value="Del" /> </td></tr>');

    RowColor();
}


 $('input[id*="AddPass"]').click(function () {
        AddPassenger();
        $('input[id*="DeletePass_"]').on('click', Del);
    });


var Del = function (DelBtn) {
        var _DeletePass = $('input[id*="DeletePass_"]')
        if (_DeletePass.length > 1) {
            $(DelBtn.currentTarget).parent().parent().remove();
            var Tr = $('#TblPassenger').find('tbody tr');
            $.each(Tr, function (i) {
                Tr.eq(i).find('td').eq(0).text(i + 1);
                var $n = i + 1;
                Tr.eq(i).find('td').eq(1).find('input').attr('placeholder', 'Name ' + $n);
            });
        }
        RowColor();
    }

function RowColor() {
    $('#TblPassenger tbody tr:odd').css('background-color', 'burlywood');
    $('#TblPassenger tbody tr:even').css('background-color', 'white');
}

2 Comments

it is showing red mark on $('.test').append( '<tr><td><input type="text" class="index_txtBox"/></td> <td><input type="checkbox" class="check_box"/></td> <td><input type="text" class="txt_Box"/></td> <td><select><option></option></select></td></tr> ');
place whole code in single line..........$('.test').append('<tr><td><input type="text" class="index_txtBox"/></td> <td><input type="checkbox" class="check_box"/></td> <td><input type="text" class="txt_Box"/></td> <td><select><option></option></select></td></tr>');

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.