jeremy
jeremy

Reputation: 653

how to use bind() instead of live()?

I'm trying to understand how to use bind in jquery.

I have a page which, after a button press, does the following code:

var html = [];
html.push('<select name="weddingturn" id="weddingturn">');
var a = firstweddingturn;
var b = Number(firstweddingturn) + 16;
while (a < b) {
  // do some code
  html.push('<option name="asdf">' + a + '</option>');
  a++;
 }  // end while
html.push('</select>');
$('#div1').append(html.join('')); 

I also want to catch any changes to that select, once it is set up.

var firstweddingturn = '400';

$('#weddingturn').live('change',function() {

  alert ("Wedding select change triggered!");

  //var wedturn = $('#weddingturnselectid').val();
  //$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')

});

I would greatly appreciate someone showing and explaining how to use bind() in this instead of live().

For context sake, please see here: jquery created select, and triggering on change

Upvotes: 2

Views: 271

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

$('#weddingturn').live('change',function(){});

This site explains the difference very well: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

Upvotes: 2

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20620

I think it depends on when you are calling live or bind - after or before those html element available. If you are calling bind after those html element is available on that page, it should be OK to swap. Otherwise, I think bind would not work.

Upvotes: 1

Kelly Sutton
Kelly Sutton

Reputation: 591

There is also a shorthand for bind() for certain events. You can make your code shorter by doing:

$('#weddingturn').change(function() {

Keep in mind though that bind() and live() do fundamentally different things. live() affects everything with the given selectors, while bind() will only bind events to elements that are already on the page.

Upvotes: 2

m.edmondson
m.edmondson

Reputation: 30922

Just swap:

$('#weddingturn').live('change',function() {

to:

$('#weddingturn').bind('change',function() {

.live should've solved your problem - so what is the exact reason or problem you're having?

Upvotes: 2

Related Questions