0

I have Generated Dynamic Table Using Following Code in C# + Mongodb

for (var i = 0; i < data.length; i++) {
                strData += "<tr>\
                   <td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
                               <td><input type='button' id='delete' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord()'></td>\
                               <td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
                               </tr>";
            }
             //$("#data").append(tabelHerader); 
            $("#data").html(strData);

Now I Want To delete Record when I click To Delete Button the Following Function Will Execute

 function deleteRecord() {
            var sid = $("#delete").attr("sid");
            alert(sid);
           // console.log("yes we are in");
            $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'Home.aspx/deleteData',
                data: "{'id':'" + sid + "'}",
                async: false,
                success: function (response) {
                    alert("you have successfully deleted record");
                },
                error: function () {
                    console.log('there is some error');
                }
            });


        }

But The Problem Is That When I Click To Delete Button I get Same Id For Each Record ,So If I Click Any Button Only First Record Will Delete. Anyone Have Solution?

5
  • change var sid = $("#delete").attr("sid"); var sid = $(this).attr("sid"); Commented Dec 25, 2017 at 6:54
  • OPtion 1 - you can add the sid/id to the tr directly to delete and Option 2 pass the sid/id to the function directly Commented Dec 25, 2017 at 6:55
  • is this question have solved? Commented Dec 25, 2017 at 7:21
  • no its not working with class,id or by passing value in function as parameter Commented Dec 25, 2017 at 7:26
  • Here is another example jsfiddle.net/mvLwymvb Commented Dec 25, 2017 at 8:00

6 Answers 6

1

Id must be unique for each element use class instead of id or simply pass id to the function as below

for (var i = 0; i < data.length; i++) {
    var sid = data[i].sid;
                strData += "<tr>\
                   <td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
                               <td><input type='button' value='delete' sid='" + data[i].sid + "' onclick='deleteRecord("+ sid +")'></td>\
                               <td><input type='button' value='update' sid='" + data[i].sid + "' onclick='updateRecord("+ sid +");'></td>\
                               </tr>";
            }
             //$("#data").append(tabelHerader); 
            $("#data").html(strData);

and in your update record or delete record function do as below

function deleteRecord(sid) {

        alert(sid);
       // console.log("yes we are in");
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'Home.aspx/deleteData',
            data: "{'id':'" + sid + "'}",
            async: false,
            success: function (response) {
                alert("you have successfully deleted record");
            },
            error: function () {
                console.log('there is some error');
            }
        });


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

5 Comments

i try both way using class its repeat same id ans using function parameter its give me Unexpected Token error
debug sid value exists and try the above
your sid is string then try to store it in a variable and then use it
but without the array how can u pass sid to the function
i have simply added a variable inside the loop and it will change for each iteration but without the array how can u pass sid to the function?
1

first, you need to change your function, add 1 argument to your function

function deleteRecord(id) {

then change var sid value to be var sid = id;

With onclick, you can use

onclick="deleteRecord(pass_some_id from data[i].sid)"

Without onclick, var sid = $("#delete").attr("sid"); will choose first sid attribute value from input list, so what you need is

$("#delete").each(function(){
  $(this).onclick(function(){
    var sid = $(this).attr("sid"); // get attr value from specify clicked button
    deleteRecord(sid); // call delete record with specify id
  })
})

or simply way :

change

var sid = $("#delete").attr("sid"); 

to

var sid = $(this).attr("sid"); // select attribute value from current clicked element

Full Example from @lukesUbuntu :

https://jsfiddle.net/mvLwymvb/

here some good reference :

  1. http://api.jquery.com/jquery.each/
  2. https://api.jquery.com/category/selectors/

7 Comments

but when i try to pass an argument in my function its give me unexpected token error , i think that is the main problem
if i pass "onclick='check("+ data[i].sid +")" this code the it is giving me Invalid or Unexpected Token error and i pass "onclick='check('"+ data[i].sid +"')" its show something like this onclick(" 5a4096c97169a0033475b51e')
right onclick(" 5a4096c97169a0033475b51e') , then make sure you have argument in your function
ups, something wrong "{'id':'" + sid + "'}" need to change to {id:sid}
i have an argument .it still give me the "unexpected tocken } " error
|
0

You can append the value of i with the id and onclick you can pass the context using this

 "<tr>" +
        "<td>" + data[i].sid + "</td>" +
        "<td> " + data[i].fname + " </td>" +
        "<td>" + data[i].lname + "</td>" +
        "<td>" + data[i].email + "</td>" +
        "<td>" + data[i].pass + "</td>" +
        "<td>" + data[i].address + "</td>" +
        "<td><input type='button' id='delete_'"+i+" value='delete' " +
                                     // ^ changed here
        "sid='" + data[i].sid + "' onclick='deleteRecord(this)'></td>" +
        "<td><input type='button' id='update_'"+i+" value='update'" +
                                  // ^ Changed here
        " sid='" + data[i].sid + "' onclick='updateRecord(this);'></td>" +
        "</tr>";

in deleteRecord function

function deleteRecord(elem){
   var getId = elem.id // id of the clicked element

}

Comments

0

Working example here https://jsfiddle.net/mvLwymvb/1/

for (var i = 0; i < data.length; i++) {
    strData += "<tr>\
    <td>" + data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
    <td><input class='delete' type='button' id='delete' value='delete' sid='" + data[i].sid + "'></td>\
    <td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
    </tr>";
  }

  //$("#data").append(tabelHerader);
  $("#data").html(strData);


  $(".delete").click(function() {
    var sid = $(this).attr("sid");
    alert(sid);
    // console.log("yes we are in");
    $.ajax({
      type: 'POST',
      contentType: "application/json; charset=utf-8",
      url: 'Home.aspx/deleteData',
      data: "{'id':'" + sid + "'}",
      async: false,
      success: function(response) {
        alert("you have successfully deleted record");
      },
      error: function() {
        console.log('there is some error');
      }
    });
  })

1 Comment

@vaibhav have you tried passing onclick='deleteRecord(this)'
0

Finally I Got The Solution And That Solution is A Deligets

  function check()
        {
            $(document).on('click', '#delete', function (event) {

                var element = event.target;
                var sid = $(element).attr("sid");
                console.log(sid);
                deleteRecord(sid);

            });

        }

        function deleteRecord(sid) {

           // console.log("yes we are in");
            $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'Home.aspx/deleteData',
                data: "{'id':'" + sid + "'}",
                async: false,
                success: function (response) {
                    alert("you have successfully deleted record");
                }   ,
                error: function () {
                    console.log('there is some error');
                }
            });

This Is Html Part

 for (var i = 0; i < data.length; i++) {
                var sid = data[i].sid
                strData += "<tr>\
                   <td>"+ data[i].sid + "</td> <td> " + data[i].fname + " </td><td>" + data[i].lname + "</td><td>" + data[i].email + "</td><td>" + data[i].pass + "</td><td>" + data[i].address + "</td>\
                               <td><input type='button' id='delete' value='delete' sid='" + sid + "' onclick='check()' ></td>\
                               <td><input type='button' id='update' value='update' sid='" + data[i].sid + "' onclick='updateRecord();'></td>\
                               </tr>";
            }

Thank You so much Every One

Comments

0

Don't mess up with native JavaScript and jQuery. You will confuse later.

First don't do inline onclick when you have jQuery, use $(elem).click(function) instead.

Second id must be unique (1 id must be used by 1 element only), class is general (1 class can be used by many element).

Try to edit this line

...
<td><input type='button' id='delete' value='delete' class="btn-delete" sid='" + data[i].sid + "' ></td>\
...

and your script

<script>
    $(function(){
        $('body').on('click', '.btn-delete', function(){
            var sid = $(this).attr("sid");
            var tr = $(this).closest('tr');
            //alert(sid);
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'Home.aspx/deleteData',
                data: {id: sid},
                //async: false, why you need to do this????
                success: function (response) {
                    console.log(response);
                    alert("you have successfully deleted record");
                    tr.remove();
                },
                error: function (response) {
                    console.log('there is some error');
                    console.log(response);
                }
            });
        }) 
    });
    </script>

Comments

Your Answer

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