1

i'm new in jQuery and i'm wonderin how to solve this issue. I marked the Delete to show the link thru this code:

$('a[id^="del"]').css('border','red 1px solid');

Initial table

The problem is when I added a new Activity thru this code:

function addGradebkhdr() {

var formData = formToJSON();

    $.ajax({
      type: 'post',
      contentType: 'application/json',
      url: 'http://samle.com/api',
      dataType: "json",
      data: formData,
      success: function(data, textStatus, jqXHR){
        **addTableGradebkhdr(data);**
      },
      error: function(jqXHR, textStatus, errorThrown){
        // handle error
      }
    });
 }

function addTableGradebkhdr(data) {

  var lr = $(".tb-gradebkhdr tbody tr:last-of-type");
  var no = parseInt($(".tb-gradebkhdr tbody tr:last-of-type td:first-of-type").text());
  var ctr = no + 1;
    var d = new Date(data.date);
    var day = d.getDate();
    var month = d.getMonth() + 1; //Months are zero based
    var year = d.getFullYear();
    var sDate = month + "/" + day + "/" + year;

    var row = '<tr id="'+ data.id +'" ><td>'+ ctr +'</td>';
            row += '<td>'+ data.criteria_name +'</td>';
            row += '<td>'+ data.rawhigh +'</td>';
            row += '<td>'+ sDate +'</td>';
            row += '<td>'+ data.quarter +'</td>';
            row += '<td>'+ data.remarks +'</td>';
            row += '<td>';
            row += '<a gradebkhdrid="'+ data.id +'" id="edit-'+ data.id +'" href="#">Edit</a> ';
            row += '<a gradebkhdrid="'+ data.id +'" id="del-'+ data.id +'" href="#">Delete</a>';
            row += '</td></tr>';
        lr.after(row);


}


$(document).ready(function(){

$("#frmBtn-grbkhdr-save").on('click',**addGradebkhdr**);

$('a[id^="del"]').each(function(){
    $(this).on("click",function() {
            var gradebkhdrid = $(this).attr('gradebkhdrid');    
        deleteGradebkhdr(gradebkhdrid);
        });     
  });
});

and the Table become like this:

fasd

as you can see the last Delete was not detected by

$('a[id^="del"]').each(function(){
    $(this).on("click",function() {            
        var gradebkhdrid = $(this).attr('gradebkhdrid');
        deleteGradebkhdr(gradebkhdrid);
     });
});

The red border was not a part of the table. I used it to track the event/error trapping. As you can see in the 1st image,the page was loaded and all the Delete link was marked red. It means the Delete link all work.

But when I added a new Activity via jQuery ajax function to submit the form and created a Table Row and its element inside including the Delete button. The added delete link was not working and the red line I created was not applied also an as you can see un the 2nd image.

1
  • Regarding adding red borders why don't you do it in your CSS stylesheet? Then it would automatically apply to dynamically added elements. You don't need JS (or jQuery) to do it. Commented Oct 2, 2012 at 6:35

7 Answers 7

1

There is two aspects to this problem, with two separate solutions.

Add a class to the delete button so that you can target them with plain CSS without changing the style of the elements directly:

row += '<a gradebkhdrid="'+ data.id +'" id="del-'+ data.id +'" class="delButton" href="#">Delete</a>';

Now you can use this CSS to set the border, and it will also work for newly added elements.

.delButton { border: 1px solid red; }

To handle the click events on added elements you use a delegate:

$('.tb-gradebkhdr').on('click', 'a[id^="del"]', function(){
  var gradebkhdrid = $(this).attr('gradebkhdrid');    
  deleteGradebkhdr(gradebkhdrid);
});     

The event handler will be bound on the table and catches the event when it bubbles up, so it will work for newly added elements too.

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

3 Comments

a better approach is using Javascript Mutation Event's developer.mozilla.org/en-US/docs/DOM/Mutation_events
@Cody: Why would that be a better approach? Why look for changes, when you can set up CSS and event handlers that works without looking for changes? Besides, on the page that you link to it says that they are deprecated because the design is flawed...
@Cody - not only are they deprecated, they never worked cross-browser.
1

So you are saying that you want to attach click event to nonexisting elements as well ( which will exist in the future )? Try this:

$(document).on( 'click', 'a[id^="del"]', function(){      
    var gradebkhdrid = $(this).attr('gradebkhdrid');
    deleteGradebkhdr(gradebkhdrid);
});

You can change document with a holder of all these rows, for example $( '#myTable' )....

As for CSS: add custom class to a tags and style it properly in a seperate stylesheet file ( or <style> tag ).

1 Comment

this works for me! i think the issue is the code: $('a[id^="del"]').each(function(){ $(this).on("click",function() { var gradebkhdrid = $(this).attr('gradebkhdrid'); deleteGradebkhdr(gradebkhdrid); }); }); });
0

you can usee live function of jQuery: http://api.jquery.com/live/

or you can add handler explicitely in function "addTableGradebkhdr" when row is creating

2 Comments

Its not yet deprecated. going to be deprecated. right now, it works.
@prem Quote from the documentation: As of jQuery 1.7, the .live() method is deprecated. Do you understand what that word means? It means exactly that it works, but will not somewhere in the future. Thus it should be avoided.
0

If you are expecting your table to have rows on page load, and your front end functions are attached at the same time, you can use jquery.clone() function to copy a previous row and alter the contents afterwards. This will save you some code and also apply previous listeners to the new element.

var newRow = $("table tr:last").clone(true);
$(newRow).find("td:eq(0)").html("new data for column 1");

$(newRow).insertAfter(row);

Comments

0

You should recall $('a[id^="del"]').css('border','red 1px solid'); you are not using CSS so border will get applied to already added elements only which you are selecting through jQuery.

...your code
....
lr.after(row);
$('a[id^="del"]').css('border','red 1px solid');

OR

you can directly set border color

row += '<a style="border:red 1px solid;" gradebkhdrid="'+ data.id +'" id="del-'+ data.id +'" href="#">Delete</a>';          

You can use jQuery.live

$('a[id^="del"]').live(function() {            
     var gradebkhdrid = $(this).attr('gradebkhdrid');
     deleteGradebkhdr(gradebkhdrid);
}); 

Comments

0

you can try with this

....
lr.after(row);
$("a[id^='del']:last").css('border', 'red 1px solid');

Comments

0

You can do this in 2 ways.

1) you can define the style in stylesheet
2) you can apply the style with javascript by calling the same line from a live binding function. you can do live binding usign jquery's on() function from http://api.jquery.com/on/
Here, as your script is using, id starts with 'del', your adding element should have delete link id that start with 'del', if you are using the same script. Its better you fix a class for that delete link and update your script line as below

$('a[class="deleteLink"]').css('border','red 1px solid');

Hope it helps.

Comments

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.