highBandWidth
highBandWidth

Reputation: 17296

jQuery bind on change of length

I have a table that is being updated by Ajax. I want to do something when new data is added to it, but since the change is in appearance, it should be done by the preloaded JS rather than Ajax returned JS.

I am looking for something like $('table tr').length.change( ... ), So I can do something like this

$('table tr').length.change( function() {
  if ($('table tr').length>1) $('table').show() else $('table').hide()
}

The Ajax-returned JS will do something like this (say in Rails)

$('table').append('<tr> <td><%= @person.name %></td> <td><%= @person.age %></td> </tr>')

(in Rails this will be in some /app/views/container_name/method_name.js.erb)

Upvotes: 2

Views: 5787

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

Just after append statement try show-hide statement.

$('table')
   .append('<tr> <td><%= @person.name %></td> <td><%= @person.age %></td> </tr>');

if( $('table tbody tr').length > 1 ) {
   $('table').show();
} else {
   $('table').hide()
}

Note:

$('table tr').length.change(..) is not valid approach. Because, .change() in an event handler that works for input, select elements those wrapped within $() i.e for jQuery Object.

For example:

$('select').change()`, `$('input').change()

Moreover, .length does not return a jQuery object. So you can't use .change() with .length and its not needed at all.

Upvotes: 0

Kevin B
Kevin B

Reputation: 95027

You could use a pub-sub approach.

$('table')
   .append('<tr> <td><%= @person.name %></td> <td><%= @person.age %></td> </tr>')
   .trigger('tableModified');

Then in your layout/design,

$('table').on('tableModified',function(){
    if ($('tr', this).length>1) $(this).show() else $(this).hide()
});

This way your table code doesn't have to be aware of your layout/design or anything else that may need to know when the table is modified.

Upvotes: 2

Florian
Florian

Reputation: 3366

I used a jQuery plugin called watch in a project way back in similiar circumstances. I had to track a lot more attributes, but it worked nicely for me:

http://darcyclarke.me/dev/watch/

Upvotes: 1

Related Questions