Search code examples
jqueryliveparent

jQuery .live and parent() problem


I have many of this snippet code:

<li>
  <label>
    <a title="Cadeo">
      <span class="container">
        <img class="shadow" src="../public/4cf54b32bd723_small.jpg" alt="" />
      </span>
    </a>
    <input name="Trailer" type="radio" value="1" />
    <span class="change">Seleziona</span>
  </label>
</li>

Thanks to this jQuery code, when clicking on tag (that contains all) the "Seleziona" text is replaced with a button tag:

$('label').click(function(){
  $('label').children('span.change').html('Seleziona'); // reset the others li's text
  $(this).children('span.change').html('<button type="button" class="small middle"><img src="../images/vota-small.png" alt="" /></button>')
})

Now comes the tricky part: I'm trying to catch the value of the radio input tag, but this doesn't work (I am using the .live function since the button is created at runtime)

$('button').live('click', function(){
  alert($(this).parent().siblings('input').val());
})

Where am I wrong? I keep getting "undefined"... Thanks in advance for the answers

If it can help, here is a live version: http://jsfiddle.net/H4Gsq/


Solution

  • First, why the parent()? The input is the sibling of the span, not the sibling of its parent. Second, both event handlers will fire when you click the button. stopPropagation is no help as live itself relies on event bubbling; also, live event handlers fire after normal event handlers. You should check event.target and if it is a button, skip the click handler of the label.

    Forget the first part, I didn't read the code carefully. Anyway, here is a corrected version: http://jsfiddle.net/H4Gsq/1/